ccnokes ccnokes - 6 months ago 28
Javascript Question

jQuery return first 5 words of a string without commas

I'm trying to return the first 5 words of a string in a readable format, no "" or commas separating words. I'm not sure if its a regex thing or what, but I can't figure it out although its probably simple. Thanks!

See what I have thus far:
http://jsfiddle.net/ccnokes/GktTd/

This is the function I'm using:

function getWords(string){
var words = string.split(/\s+/).slice(1,5);
return words;
}

Answer

The only thing you are missing is a join()

Try this:

function getWords(str) {
    return str.split(/\s+/).slice(0,5).join(" ");
}

This will do something like:

var str = "This is a long string with more than 5 words.";
console.log(getWords(str)); // << outputs "This is a long string"

Take a look at this link for a further explanation of the .join(). function in javascript. Essentially - if you don't supply an argument, it uses the default delimiter ,, whereas if you supply one (as I'm doing in the above example, by providing " " - it will use that instead. This is why the output becomes the first 5 words, separated by a space between each.

Comments