Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search replace with regex and keep case as original in javascript

Tags:

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?

like image 773
Graham Avatar asked Dec 05 '12 11:12

Graham


People also ask

Can you use regex in Find and Replace?

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.

How do you replace all occurrences of a regex pattern in a string?

sub() method will replace all pattern occurrences in the target string.

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

What does regex (? S match?

i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.


1 Answers

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/

like image 197
DhruvPathak Avatar answered Oct 08 '22 06:10

DhruvPathak