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.
For example:
var s1 = "abC...ABc..aBC....abc...ABC";
var s2 = s.replace(/some clever regex for abc/g, "#"+original abc match+"#");
The result in s2 should end up like:
"#abC#...#ABc#..#aBC#....#abc#...#ABC#"
Can this be done with regex? If so, how?
When you want to search and replace specific patterns of text, use regular expressions. They can help you in pattern matching, parsing, filtering of results, and so on. Once you learn the regex syntax, you can use it for almost any language. Press Ctrl+R to open the search and replace pane.
sub() method will replace all pattern occurrences in the target string.
For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.
i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With