简体   繁体   中英

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM