admin管理员组文章数量:1431997
i am using my_colors.split(" ") method, but i want to split or divide string in fixed number of words e.g each split occurs after 10 words or so ...how to do this in javascript?
i am using my_colors.split(" ") method, but i want to split or divide string in fixed number of words e.g each split occurs after 10 words or so ...how to do this in javascript?
Share Improve this question asked Feb 18, 2010 at 6:21 SheerySheery 1,1335 gold badges14 silver badges23 bronze badges4 Answers
Reset to default 7Try this - this regex captures groups of ten words (or less, for the last words):
var groups = s.match(/(\S+\s*){1,10}/g);
You might use a regex like /\S+/g
to split the string in case the words are separated by multiple spaces or any other whitespace.
I am not sure my example below is the most elegant way to go about it, but it works.
<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>
You can split(" ") then join(" ") the resulting array 10 elements at a time.
You can try something like
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"]
But you better do either split(" ")
and then join(" ")
or write a simple tokenizer yourself that will split this string in any way you like.
本文标签: Strings split in javascriptStack Overflow
版权声明:本文标题:Strings split in javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745566158a2663772.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论