Sheery
Sheery

Reputation: 1133

Strings split 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?

Upvotes: 4

Views: 402

Answers (4)

Kobi
Kobi

Reputation: 137997

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

var groups = s.match(/(\S+\s*){1,10}/g);

Upvotes: 7

jessegavin
jessegavin

Reputation: 75640

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>

Upvotes: 3

vava
vava

Reputation: 25371

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.

Upvotes: 0

marklai
marklai

Reputation: 2040

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

Upvotes: 2

Related Questions