如何在JavaScript中将大字符串拆分为n个大小的块?
有两种方法可以将大字符串拆分为n个大小的子字符串。
1)常规方法
这是一种纯逻辑方法,其中仅使用常规方法(例如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
2)正则表达式方法
这不是预定的方法。正则表达式方法提供了一个插槽来提及将字符串分块的大小。
通常,对于要从中提取最多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"]
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿