我正在使用my_colors.split(“”)方法,但我想在固定数量的单词中拆分或分割字符串,例如每个拆分发生在10个字左右之后...如何在javascript中执行此操作?
答案 0 :(得分:7)
试试这个 - 这个正则表达式捕获十个单词组(或更少,最后一个单词):
var groups = s.match(/(\S+\s*){1,10}/g);
答案 1 :(得分:3)
如果单词由多个空格或任何其他空格分隔,您可以使用像/\S+/g
这样的正则表达式来拆分字符串。
我不确定下面的例子是最优雅的方式,但它确实有用。
<html>
<head>
<script type="text/javascript">
var str = "one two three four five six seven eight nine ten "
+ "eleven twelve thirteen fourteen fifteen sixteen "
+ "seventeen eighteen nineteen twenty twenty-one";
var words = str.match(/\S+/g);
var arr = [];
var temp = [];
for(var i=0;i<words.length;i++) {
temp.push(words[i]);
if (i % 10 == 9) {
arr.push(temp.join(" "));
temp = [];
}
}
if (temp.length) {
arr.push(temp.join(" "));
}
// Now you have an array of strings with 10 words (max) in them
alert(" - "+ arr.join("\n - "));
</script>
</head>
<body>
</body>
</html>
答案 2 :(得分:2)
您可以拆分(“”),然后一次加入(“”)生成的数组10个元素。
答案 3 :(得分:0)
您可以尝试类似
的内容console.log("word1 word2 word3 word4 word5 word6"
.replace(/((?:[^ ]+\s+){2})/g, '$1{special sequence}')
.split(/\s*{special sequence}\s*/));
//prints ["word1 word2", "word3 word4", "word5 word6"]
但你最好做split(" ")
然后join(" ")
或自己编写一个简单的标记器,以任何你喜欢的方式分割这个字符串。