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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:46:25  来源:igfitidea点击:

Get second and third words from string

javascript

提问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

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

使用 stringsplit()将字符串按空格拆分:

var words = string1.split(' ');

Then access the words using:

然后使用以下方法访问单词:

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

回答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 .lengthproperty to avoid getting undefinedin 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(" ");