Saravanan
Saravanan

Reputation: 1237

javascript RegEX with round brackets in pattern

The below script is returning null. It is returning correctly if I remove round brackets in str and patt1 for the text spot_Northeast(300)_comment

<script type="text/javascript">
var str="0000CentralGasEform2,0000CentralGasEformNew,spot_Northeast(300)_comment"; 
var patt1=/\bspot_Northeast(300)_comment/g;
document.write(str.match(patt1));
</script>

In my application, the value in str is taken from the cookies and the value in patt1 is dynamic based on the window opened

regExp = new RegExp('\\b'+FormOpen+'\\b', 'g'); 

Here FormOpen is dynamic. Then I replace the match in cookie

var temp=CookieList.replace(regExp,""); 

Is there a way to tell RegEX that () is normal text instead of hardcoding?

Upvotes: 3

Views: 4543

Answers (3)

Evert
Evert

Reputation: 8541

Escape the brackets:

var patt1=/\bspot_Northeast\(300\)_comment/g;

Upvotes: 0

Misam
Misam

Reputation: 4389

You need to escape the round braces with '\' escape character as they have special meaning in reg ex your reg ex would look something like..

var patt1=/\bspot_Northeast\(300\)_comment/

Upvotes: 0

j_mcnally
j_mcnally

Reputation: 6958

escape them

var patt1=/\bspot_Northeast\(300\)_comment/g;

() are reserved characters in the context (.*) for instance, you need to tell the regex engine to treat them as normal text through a process called escaping

Upvotes: 4

Related Questions