Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unmatched ) in Javascript regular expression [closed]

May be you can help me: My javascript code:

bbchatdecode: function(text) {  

var chars = Array(":\\)","8-\\)",":cry:",":oops:");
var replacements = Array('<img src=\"smiley-smile.gif\" alt=\":)\">','<img src=\"smiley-cool.gif\" alt=\"8-)\">','<img src=\"smiley-cry.gif\" alt=\":cry:\">','<img src=\"smiley-embarassed.gif\" alt=\"oops:\">');
for (var ic=0; ic<chars.length; ic++) {
  var re = new RegExp(chars[ic], "gi");
  if(re.test(text))
  {
   text = text.replace(re, replacements[ic]);
  }
}
return text;
}   

But in the browser I can see:

unmatched ) in regular expression

like image 647
XTRUST.ORG Avatar asked Oct 25 '11 06:10

XTRUST.ORG


2 Answers

Unmatched ) in Javascript regular expression error occurs when some of your string contains ')'. You need to escape this. Here is the function to do that:

function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
like image 73
Arvind Bhardwaj Avatar answered Sep 18 '22 23:09

Arvind Bhardwaj


Valid regexp string is: :\\\). You should triple-repeat backslash in order to escape something from string. When you are constructing your regexp as raw JS (e.g. var re = /:\)/;) you do not to do that.

Sorry, but i can not explain why this happens for now.

like image 30
shybovycha Avatar answered Sep 19 '22 23:09

shybovycha