uneatenbreakfast
uneatenbreakfast

Reputation: 615

Different behaviours when using regex in javascript

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;

Upvotes: 2

Views: 43

Answers (1)

Musa
Musa

Reputation: 97672

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

"([^\\s]+\\s){0,5}"+query+"([^\\s]+\\s){0,5}"

Upvotes: 4

Related Questions