2

I'm using javascript and regex to scan a sentence for a particular word('schiz') then return the match along with 5 words in front of and behind my queried word.

However, I seem to be running into an odd situation, where the "new Regexp()" object doesn't behave the same way as just using the plain regex form.

In the following code, if I use:

reg = /([^\s]+\s){0,5}schiz([^\s]+\s){0,5}/g

then it returns as expected, but since I need the query word to be a variable, I need to use "new regexp()" to create my regex.

reg = RegExp("([^\s]+\s){0,5}"+query+"([^\s]+\s){0,5}","g");

Where query is "schiz", doesn't give the same result, can anyone explain why this is the case? Here is the entire snippet:

    var matchItem = "<p><strong>Indications</strong></p>&#10;<p>- Used to treat &#34;resistant schizophrenia&#34; (resistant meaning pt has tried 2 other antipsychotics to little effect)</p>&#10;<p>- Better for refractory schizophrenia than chlorpromazine</p>";
    var query = "schiz";


    var reg = RegExp("([^\s]+\s){0,5}"+query+"([^\s]+\s){0,5}","g");
    //reg = /([^\s]+\s){0,5}schiz([^\s]+\s){0,5}/g

    var ms = ("" + matchItem).match(reg);
    if(ms!=null){
        ms = ms.join("...");
    }

    return ms;
3
  • Did you forget the "new" keyword? Commented Dec 30, 2014 at 0:08
  • 2
    You need to escape your \​s. Commented Dec 30, 2014 at 0:09
  • Pasting the var query... and var reg lines into the console would have shown you that (as @SLaks pointed out) the output is /([^s]+s){0,5}schitz([^s]+s){0,5}/g. Commented Dec 30, 2014 at 0:12

1 Answer 1

4

\ is a special character in a string literal, you have to escape it

"([^\\s]+\\s){0,5}"+query+"([^\\s]+\\s){0,5}"
Sign up to request clarification or add additional context in comments.

Comments

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.