user2840278
user2840278

Reputation: 281

JavaScript Regex select a word between two words

Helllo, ajax request returs me a string, that I store in a variable:

text = "bla bla bla word1 unknown. Word2 bla bla bla";

I know the every word in the text except the 'unknown'. I need to store the 'unknown' word in a variable to do further work. I know that it can be done by Regex, but I don't quite understand it. Can someone show me the trick? Thank you for your time!

Upvotes: 3

Views: 2522

Answers (2)

Amit
Amit

Reputation: 1011

You can use a simple .match like this.

text = "bla bla bla word1 word i want Word2 bla bla bla";
myWord = text.match("word1(.*)Word2")[1];
console.log(myWord);

Upvotes: 1

abiessu
abiessu

Reputation: 1927

word1\s+([^.]*).\s*Word2 should do it.

More generally,

word1\s+(\S+)\s+[wW]ord2

This will find the "word" (non-space characters) preceded by "word1" and followed by "word2" or "Word2". The only thing possibly necessary would be to remove non-word characters (like the period).

Upvotes: 0

Related Questions