javascript 从字符串中获取第二个和第三个单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16223043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get second and third words from string
提问by Max Hendersson
I have strings in jQuery:
我在 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 = ???;
采纳答案by yowza
First, you don't have strings and variables "in jQuery". jQuery has nothing to do with this.
首先,“jQuery”中没有字符串和变量。jQuery 与此无关。
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.
这将为您提供第二个结果的第一个词。
回答by hek2mgl
回答by Ejaz
Just to add to the possible solutions, the technique using split()
will fail if the string has multiple spaces in it.
只是为了添加可能的解决方案,split()
如果字符串中有多个空格,则使用的技术将失败。
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.
也不要忘记使用.length
属性检查数组长度以避免进入undefined
变量。
回答by Mani
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
你可以通过 temp.length 检查你有多少字
回答by Ioannis Potouridis
const string = "The lake is a long way from here."
const string = "湖离这里很远。"
const [,second,third,] = string.split(" ");
const [,second,third,] = string.split(" ");