Upalr
Upalr

Reputation: 2148

Find the next word after matching a word in Javascript

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"

Upvotes: 1

Views: 8085

Answers (3)

Alberto Trindade Tavares
Alberto Trindade Tavares

Reputation: 10366

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

Upvotes: 4

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32869

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

Upvotes: 3

Hassan Imam
Hassan Imam

Reputation: 22534

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

Upvotes: 1

Related Questions