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?

4 Answers 4

7

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

var groups = s.match(/(\S+\s*){1,10}/g);
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@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.
3

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>

3 Comments

Slice can come in handy here: w3schools.com/jsref/jsref_slice_array.asp
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.
thanks "jessegavin", it does what i exactly want thanks alot.
2

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.