在Javascript中找到匹配单词后面的下一个单词

时间:2017-07-04 16:32:41

标签: javascript string

想要在字符串“申请2次保险”之后获得第一个字。

var Number = 2;
var text = "Apply for 2 insurances or more";

在这种情况下,我想在Number之后得到字符串,所以我的预期结果是“保险”

3 个答案:

答案 0 :(得分:2)

findIndex的解决方案只能获得数字后的单词:

var number = 2;
var text = "Apply for 2 insurances or more";
var words = text.split(' ');

var numberIndex = words.findIndex((word) => word == number);
var nextWord = words[numberIndex + 1];

console.log(nextWord);

答案 1 :(得分:1)

您可以简单地使用正则表达式来获取数字后的第一个单词,如此...

var number = 2;
var text = "Apply for 2 insurances test";
var result = text.match(new RegExp(number + '\\s(\\w+)'))[1];

console.log(result);

答案 2 :(得分:0)

var number = 2;
var sentence = "Apply for 2 insurances or more";

var othertext = sentence.substring(sentence.indexOf(number) + 1);
console.log(othertext.split(' ')[1]);

//With two split
console.log(sentence.split(number)[1].split(' ')[1]);