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.