Skip to content Skip to sidebar Skip to footer

Get Second And Third Words From String

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

Solution 1:

Use string split() to split the string by spaces:

var words = string1.split(' ');

Then access the words using:

var word0 = words[0];
var word1 = words[1];
// ...

Solution 2:

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.

Solution 3:

Just to add to the possible solutions, the technique using split() will fail if the string has multiple spaces in it.

var arr = "   word1   word2    ".split(' ')

//arr is ["", "", "", "word1", "", "", "word2", "", "", "", ""]

To avoid this problem, use following

var arr = "   word1   word2    ".match(/\S+/gi)

//arr is ["word1", "word2"]

and then the usual,

var word1 = arr[0];
var word2 = arr[1]
//etc 

also don't forget to check your array length using .length property to avoid getting undefined in your variables.

Solution 4:

var temp = string1.split(" ")//now you have 3 words in temp
temp[1]//is your second word
temp[2]// is your third word

you can check how many words you have by temp.length

Solution 5:

const string = "The lake is a long way from here."

const [,second,third,] = string.split(" ");

Post a Comment for "Get Second And Third Words From String"