Regular Expression with Replace method in Javascript

In Javascript Replace method, regular expressions can also be used. Even for basic ones, user can benefit from regular expressions. For instance, replace method works only for once and case sensitive but regular expression can be configured to be replaceAll and case-instensitive.

I prepared a demo usage of regex which replaces the string with following criteria:
[xyz]= green
['xyz']= darkred
AND= red

var htmlstr= document.getElementById('test').innerHTML;
htmlstr = htmlstr.replace(/\[([^',\]]*[^'])\]/g, "["+ "$1"+"]");
htmlstr = htmlstr.replace(/\['([^']*)'\]/g, "['"+ "$1"+"']");
htmlstr = htmlstr.replace(/\sand\s/gi, " AND ");


No comments:

Post a Comment