有两种方法可以将大字符串拆分为n个大小的子字符串。
这是一种纯逻辑方法,其中仅使用常规方法(例如for循环,连接,模数等)。此方法不像regex方法那样复杂,因为它是预定方法。在开始编码之前,应预先确定要分割的字符串的块数。
在以下示例中,字符串“ tutorixtutorixtutorix”被分为3个子字符串块。
<html>
<body>
<script>
var v = [];
var str = "tutorixtutorixtutorix"
var t = str.split("");
document.write(t);
document.write("</br>");
for (var i = 0; i< t.length; i++){
if((i % 3) == 2){
v.push(t[i-2].concat(t[i-1],t[i]));
}
}
document.write(v);
</script>
</body>
</html>tut,ori,xtu,tor,ixt,uto,rix
这不是预定的方法。正则表达式方法提供了一个插槽来提及将字符串分块的大小。
通常,对于要从中提取最多n个大小的子字符串的任何字符串,语法为
str.match(/.{1,n}/g); // Replace n with the size of the substring如果字符串包含任何换行符或回车符,则语法为
str.match(/(.|[\r\n]){1,n}/g); // Replace n with the size of the substring该代码的原始语法为
function chunkString(str, size) {
return str.match(new RegExp('.{1,' + size + '}', 'g'));
}<html>
<body>
<script>
stringChop = function(str, size){
if (str == null)
return [];
str = String(str);
return size > 0 ? str.match(new RegExp('.{1,' + size + '}', 'g')) : [str];
}
document.write(stringChop('nhooo'));
document.write("<br>");
document.write(stringChop('tutorix',2));
document.write("<br>");
document.write(stringChop('nhooo',3));
</script>
</body>
</html>["nhooo"] ["tu","to","ri","x"] ["tut","ori","als","poi","nt"]