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;
}
The only thing you are missing is a
join()Try this:
This will do something like:
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.