Javascript 如何将字符串拆分为 n 个字符的段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6259515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I split a string into segments of n characters?
提问by Ben
As the title says, I've got a string and I want to split into segments of ncharacters.
正如标题所说,我有一个字符串,我想分成n 个字符的段。
For example:
例如:
var str = 'abcdefghijkl';
after some magic with n=3
, it will become
经过一些魔法之后n=3
,它会变成
var arr = ['abc','def','ghi','jkl'];
Is there a way to do this?
有没有办法做到这一点?
回答by David Tang
var str = 'abcdefghijkl';
console.log(str.match(/.{1,3}/g));
Note:Use {1,3}
instead of just {3}
to include the remainder for string lengths that aren't a multiple of 3, e.g:
注意:使用{1,3}
而不仅仅是{3}
包含不是 3 倍数的字符串长度的余数,例如:
console.log("abcd".match(/.{1,3}/g)); // ["abc", "d"]
A couple more subtleties:
还有一些微妙之处:
- If your string may contain newlines (which you want to count as a character rather than splitting the string), then the
.
won't capture those. Use/[\s\S]{1,3}/
instead. (Thanks @Mike). - If your string is empty, then
match()
will returnnull
when you may be expecting an empty array. Protect against this by appending|| []
.
- 如果您的字符串可能包含换行符(您想将其视为一个字符而不是拆分字符串),则
.
不会捕获这些。使用/[\s\S]{1,3}/
来代替。(感谢@Mike)。 - 如果您的字符串为空,则在您可能需要一个空数组时
match()
返回null
。通过附加|| []
.
So you may end up with:
所以你可能会得到:
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) || []);
回答by alex
回答by maerics
str.match(/.{3}/g); // => ['abc', 'def', 'ghi', 'jkl']
回答by Mr. Polywhirl
Building on the previous answers to this question; the following function will split a string (str
) n-number (size
) of characters.
建立在之前对这个问题的回答的基础上;以下函数将拆分一个字符串 ( str
) n 个 ( size
) 字符。
function chunk(str, size) {
return str.match(new RegExp('.{1,' + size + '}', 'g'));
}
Demo
演示
(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;
}
}());
#out {
white-space: pre;
font-size: 0.8em;
}
<div id="out"></div>
回答by Jesus Gonzalez
My solution (ES6 syntax):
我的解决方案(ES6 语法):
const source = "8d7f66a9273fc766cd66d1d";
const target = [];
for (
const array = Array.from(source);
array.length;
target.push(array.splice(0,2).join(''), 2));
We could even create a function with this:
我们甚至可以用这个创建一个函数:
function splitStringBySegmentLength(source, segmentLength) {
if (!segmentLength || segmentLength < 1) throw Error('Segment length must be defined and greater than/equal to 1');
const target = [];
for (
const array = Array.from(source);
array.length;
target.push(array.splice(0,segmentLength).join('')));
return target;
}
Then you can call the function easily in a reusable manner:
然后,您可以以可重用的方式轻松调用该函数:
const source = "8d7f66a9273fc766cd66d1d";
const target = splitStringBySegmentLength(source, 2);
Cheers
干杯
回答by seriouspat
const chunkStr = (str, n, acc) => {
if (str.length === 0) {
return acc
} else {
acc.push(str.substring(0, n));
return chunkStr(str.substring(n), n, acc);
}
}
const str = 'abcdefghijkl';
const splittedString = chunkStr(str, 3, []);
Clean solution without REGEX
不含 REGEX 的清洁解决方案
回答by Alexander Mills
Here we intersperse a string with another string every n characters:
在这里,我们每隔 n 个字符将一个字符串与另一个字符串穿插在一起:
export const intersperseString = (n: number, intersperseWith: string, str: string): string => {
let ret = str.slice(0,n), remaining = str;
while (remaining) {
let v = remaining.slice(0, n);
remaining = remaining.slice(v.length);
ret += intersperseWith + v;
}
return ret;
};
if we use the above like so:
如果我们像这样使用上面的:
console.log(splitString(3,'|', 'aagaegeage'));
we get:
我们得到:
aag|aag|aeg|eag|e
aag|aag|aeg|eag|e
and here we do the same, but push to an array:
在这里我们做同样的事情,但推送到一个数组:
export const sperseString = (n: number, str: string): Array<string> => {
let ret = [], remaining = str;
while (remaining) {
let v = remaining.slice(0, n);
remaining = remaining.slice(v.length);
ret.push(v);
}
return ret;
};
and then run it:
然后运行它:
console.log(sperseString(5, 'foobarbaztruck'));
we get:
我们得到:
[ 'fooba', 'rbazt', 'ruck' ]
[ 'fooba', 'rbazt', 'ruck' ]
if someone knows of a way to simplify the above code, lmk, but it should work fine for strings.
如果有人知道简化上述代码的方法,lmk,但它应该适用于字符串。
回答by Dave Brown
function chunk(er){
return er.match(/.{1,75}/g).join('\n');
}
Above function is what I use for Base64 chunking. It will create a line break ever 75 characters.
以上函数是我用于 Base64 分块的函数。它将创建一个每 75 个字符的换行符。
回答by Maciej Sikora
Some clean solution without using regular expressions:
一些不使用正则表达式的干净解决方案:
/**
* Create array with maximum chunk length = maxPartSize
* It work safe also for shorter strings than part size
**/
function convertStringToArray(str, maxPartSize){
const chunkArr = [];
let leftStr = str;
do {
chunkArr.push(leftStr.substring(0, maxPartSize));
leftStr = leftStr.substring(maxPartSize, leftStr.length);
} while (leftStr.length > 0);
return chunkArr;
};
Usage example - https://jsfiddle.net/maciejsikora/b6xppj4q/.
使用示例 - https://jsfiddle.net/maciejsikora/b6xppj4q/。
I also tried to compare my solution to regexp one which was chosen as right answer. Some test can be found on jsfiddle - https://jsfiddle.net/maciejsikora/2envahrk/. Tests are showing that both methods have similar performance, maybe on first look regexp solution is little bit faster, but judge it Yourself.
我还尝试将我的解决方案与被选为正确答案的正则表达式进行比较。一些测试可以在 jsfiddle 上找到 - https://jsfiddle.net/maciejsikora/2envahrk/。测试表明这两种方法具有相似的性能,也许乍一看正则表达式解决方案要快一点,但请自行判断。
回答by Денис Дечев
With .split
:
与.split
:
var arr = str.split( /(?<=^(?:.{3})+)(?!$)/ ) // [ 'abc', 'def', 'ghi', 'jkl' ]
and .replace
will be:
并且.replace
将是:
var replaced = str.replace( /(?<=^(.{3})+)(?!$)/g, ' || ' ) // 'abc || def || ghi || jkl'
/(?!$)/
is to to stop before end/$/
, without is:
/(?!$)/
是在结束前停止/$/
,没有是:
var arr = str.split( /(?<=^(?:.{3})+)/ ) // [ 'abc', 'def', 'ghi', 'jkl' ] // I don't know why is not [ 'abc', 'def', 'ghi', 'jkl' , '' ], comment?
var replaced = str.replace( /(?<=^(.{3})+)/g, ' || ') // 'abc || def || ghi || jkl || '
ignoring group /(?:
...)/
is no need in .replace
but in .split
is adding groups to arr:
忽略组/(?:
...)/
不需要 in.replace
但 in.split
是向 arr 添加组:
var arr = str.split( /(?<=^(.{3})+)(?!$)/ ) // [ 'abc', 'abc', 'def', 'abc', 'ghi', 'abc', 'jkl' ]