tags:

views:

98

answers:

4

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?

+2  A: 

You can split(" ") then join(" ") the resulting array 10 elements at a time.

marklai
A: 

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.

vava
+3  A: 

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>
jessegavin
Slice can come in handy here: http://www.w3schools.com/jsref/jsref_slice_array.asp
Kobi
Good call on the slice. However, I am going to have to print out my answer just so that I can burn it. Yours is so much better.
jessegavin
thanks "jessegavin", it does what i exactly want thanks alot.
Sheery
+7  A: 

Try this - this regex captures groups of ten words (or less, for the last words):

var groups = s.match(/(\S+\s*){1,10}/g);
Kobi
Holy smokes! I feel almost embarrassed at how much more beautiful your answer is than mine! sheery, if you don't accept this answer, I will kick a puppy.
jessegavin
i also like this one ... very much ... plz dont kick a puppy ...
Sheery
@sheery If you like the answer, why dont you accept it? The answer that you find most helpful should always be accepted so the next person that has the same problem will know what solution was "best" or at least deemed best by the asker.
jmein