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 = ???;
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];
// ...
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.
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
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.
const string = "The lake is a long way from here."
const [,second,third,] = string.split(" ");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.