Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
137
rated 0 times [  142] [ 5]  / answers: 1 / hits: 17335  / 12 Years ago, tue, october 30, 2012, 12:00:00

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;
}

More From » jquery

 Answers
5

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.


[#82272] Monday, October 29, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stefanicarolinat

Total Points: 145
Total Questions: 91
Total Answers: 93

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
stefanicarolinat questions
Mon, Nov 15, 21, 00:00, 3 Years ago
Fri, Apr 16, 21, 00:00, 3 Years ago
Thu, Oct 15, 20, 00:00, 4 Years ago
Fri, Jul 17, 20, 00:00, 4 Years ago
;