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"
- 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
3 Answers
Reset to default 4A 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]);