Ben*_*Ben 171 javascript arrays string split
正如标题所说,我有一个字符串,我想分成长度为n个字符的段.
例如:
var str = 'abcdefghijkl';
Run Code Online (Sandbox Code Playgroud)
在n = 3的一些魔法之后,将成为
var arr = ['abc','def','ghi','jkl'];
Run Code Online (Sandbox Code Playgroud)
有一种优雅的方式来做到这一点?
Dav*_*ang 321
var str = 'abcdefghijkl';
console.log(str.match(/.{1,3}/g));
Run Code Online (Sandbox Code Playgroud)
注意:使用{1,3}
而不是仅{3}
包括不是3的倍数的字符串长度的余数,例如:
console.log("abcd".match(/.{1,3}/g)); // ["abc", "d"]
Run Code Online (Sandbox Code Playgroud)
更多细微之处:
.
将不会捕获这些换行符.请/[\s\S]{1,3}/
改用.(谢谢@Mike).match()
会返回null
.通过附加来防止这种情况|| []
.所以你最终会得到:
var str = 'abcdef \t\r\nghijkl';
var parts = str.match(/[\s\S]{1,3}/g) || [];
console.log(parts);
console.log(''.match(/[\s\S]{1,3}/g) || []);
Run Code Online (Sandbox Code Playgroud)
ale*_*lex 37
如果你不想使用正则表达式......
var chunks = [];
for (var i = 0, charsLength = str.length; i < charsLength; i += 3) {
chunks.push(str.substring(i, i + 3));
}
Run Code Online (Sandbox Code Playgroud)
...否则正则表达式解决方案非常好:)
mae*_*ics 20
str.match(/.{3}/g); // => ['abc', 'def', 'ghi', 'jkl']
Run Code Online (Sandbox Code Playgroud)
如果您确实需要坚持.split
和/或.raplace
,那么使用/(?<=^(?:.{3})+)(?!$)/g
为了.split
:
var arr = str.split( /(?<=^(?:.{3})+)(?!$)/ )
// [ 'abc', 'def', 'ghi', 'jkl' ]
Run Code Online (Sandbox Code Playgroud)
为了.replace
:
var replaced = str.replace( /(?<=^(?:.{3})+)(?!$)/g, ' || ' )
// 'abc || def || ghi || jkl'
Run Code Online (Sandbox Code Playgroud)
/(?!$)/
是不要停在字符串的末尾。没有它的是:
var arr = str.split( /(?<=^(?:.{3})+)/ )
// [ 'abc', 'def', 'ghi', 'jkl' ] // is fine
var replaced = str.replace( /(?<=^(.{3})+)/g, ' || ')
// 'abc || def || ghi || jkl || ' // not fine
Run Code Online (Sandbox Code Playgroud)
忽略组/(?:
...)/
是为了防止数组中出现重复的条目。没有它的是:
var arr = str.split( /(?<=^(.{3})+)(?!$)/ )
// [ 'abc', 'abc', 'def', 'abc', 'ghi', 'abc', 'jkl' ] // not fine
var replaced = str.replace( /(?<=^(.{3})+)(?!$)/g, ' || ' )
// 'abc || def || ghi || jkl' // is fine
Run Code Online (Sandbox Code Playgroud)
在此问题的先前答案的基础上; 以下函数将拆分字符串的string(str
)n-number(size
).
function chunk(str, size) {
return str.match(new RegExp('.{1,' + size + '}', 'g'));
}
Run Code Online (Sandbox Code Playgroud)
(function() {
function chunk(str, size) {
return str.match(new RegExp('.{1,' + size + '}', 'g'));
}
var str = 'HELLO WORLD';
println('Simple binary representation:');
println(chunk(textToBin(str), 8).join('\n'));
println('\nNow for something crazy:');
println(chunk(textToHex(str, 4), 8).map(function(h) { return '0x' + h }).join(' '));
// Utiliy functions, you can ignore these.
function textToBin(text) { return textToBase(text, 2, 8); }
function textToHex(t, w) { return pad(textToBase(t,16,2), roundUp(t.length, w)*2, '00'); }
function pad(val, len, chr) { return (repeat(chr, len) + val).slice(-len); }
function print(text) { document.getElementById('out').innerHTML += (text || ''); }
function println(text) { print((text || '') + '\n'); }
function repeat(chr, n) { return new Array(n + 1).join(chr); }
function textToBase(text, radix, n) {
return text.split('').reduce(function(result, chr) {
return result + pad(chr.charCodeAt(0).toString(radix), n, '0');
}, '');
}
function roundUp(numToRound, multiple) {
if (multiple === 0) return numToRound;
var remainder = numToRound % multiple;
return remainder === 0 ? numToRound : numToRound + multiple - remainder;
}
}());
Run Code Online (Sandbox Code Playgroud)
#out {
white-space: pre;
font-size: 0.8em;
}
Run Code Online (Sandbox Code Playgroud)
<div id="out"></div>
Run Code Online (Sandbox Code Playgroud)
var str = 'abcdefghijkl';
var res = str.match(/.../g)
console.log(res)
Run Code Online (Sandbox Code Playgroud)
这里的点数决定了每个单词中需要多少文本。