3

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!

2
  • 1
    Did you look up Regex with doctor google? What did you try? Commented Nov 4, 2013 at 23:47
  • 1
    If it's always a fixed length string, just use substr() to extract the portion. Commented Nov 4, 2013 at 23:47

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

Sorry for a dumb question, but how to save this in a variable? Like this? data = RegExp('word1'\s+([^.]*).\s*'word2', data);
new Regexp(word1 + "regex" + word2). Remember to escape anything that uses a backslash with another backslash. Example: var regex = /\w/ is the same as var regex = new RegExp("\\w").

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.