我正在使用my_colors.split(" ")方法,但我想将字符串按固定的单词数拆分或分割,例如每10个单词后进行一次拆分...如何在JavaScript中实现这一点?
var groups = s.match(/(\S+\s*){1,10}/g);
如果单词之间由多个空格或其他空白字符分隔,您可以使用正则表达式/\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>
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(" ")
,或者编写一个简单的分词器,以任何你喜欢的方式对这个字符串进行分割。