最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

string - Find the next word after matching a word in Javascript - Stack Overflow

programmeradmin2浏览0评论

Want to get the first word after the number from the string "Apply for 2 insurances".

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

In this case i want to get the string after the Number, So my expected result is "insurances"

Want to get the first word after the number from the string "Apply for 2 insurances".

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

In this case i want to get the string after the Number, So my expected result is "insurances"

Share Improve this question edited May 4, 2020 at 3:54 Upalr asked Jul 4, 2017 at 16:32 UpalrUpalr 2,1482 gold badges25 silver badges33 bronze badges 1
  • better will be to break the string into array and then match and once it matches(suppose array[i]) then get array[i+1] – Harpreet Singh Commented Jul 4, 2017 at 16:36
Add a ment  | 

3 Answers 3

Reset to default 4

A solution with findIndex that gets only the word after the number:

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);

You can simply use Regular Expression to get the first word after a number, like so ...

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

console.log(result);

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]);

发布评论

评论列表(0)

  1. 暂无评论