Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get second and third words from string

Tags:

javascript

I have strings in jQuery:

var string1 = 'Stack Exchange premium';
var string2 = 'Similar Questions'; //  only two
var string3 = 'Questions that may already have your answer';

How can i get from this second and third words?

var second1 = ???;
var third1 = ???;
var second2 = ???;
var third2 = ???;
var second3 = ???;
var third3 = ???;
like image 243
Max Hendersson Avatar asked Apr 25 '13 19:04

Max Hendersson


1 Answers

First, you don't have strings and variables "in jQuery". jQuery has nothing to do with this.

Second, change your data structure, like this:

var strings = [
    'Stack Exchange premium',
    'Similar Questions',
    'Questions that may already have your answer'
];

Then create a new Array with the second and third words.

var result = strings.map(function(s) {
    return s.split(/\s+/).slice(1,3);
});

Now you can access each word like this:

console.log(result[1][0]);

This will give you the first word of the second result.

like image 143
yowza Avatar answered Sep 18 '22 03:09

yowza