Here is my problem. I have a string with mixed case in it. I want to search regardless of case and then replace the matches with some characters either side of the matches.
This can be done using a callback function for regex replace.
var s1 = "abC...ABc..aBC....abc...ABC";
var s2 = s1.replace(/abc/ig, function (match) {
return "#" + match + "#" ;
}
);
alert(s2);
demo : http://jsfiddle.net/dxeE9/
This can be done using a back-reference:
var s2 = s.replace(/your complex regex/g, "#$&#");
The back-reference $&
brings in the entire match. If you want to match "abc" in any case:
var s2 = s.replace(/abc/ig, "#$&#");
If you only want to bring in part of a larger pattern, you can refer to it by its group number:
var s2 = s.replace(/some (part) of a string/ig, "#$1#");
Groups are numbered by their opening parenthesis, from left to right, from $1
to $9
.
You can also do this
yourString.replace(/([a-z]+)/ig, "#$1#")