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

3

26

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?

Hm answered 5/12, 2012 at 11:1 Comment(0)
K
51

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 + "#";
});

console.log(s2);
Kidney answered 5/12, 2012 at 11:2 Comment(8)
Sounds promising, can you give me an exampleHm
@Hm mine isn't briliant? ;-) It's shorter and probably faster ;-)Roca
@JanDvorak Your answer is equally brilliant, but IMHO callback functions provide more flexibility to operate over the matches as compared to expressions with backreferences.Kidney
@Kidney I agree that callbacks are very flexible and good to learn ;-)Roca
@JanDvorak Callbacks may provide more flexibility and are good to know but they are slower when compared to using backreferences. See this JSPerfThigmotropism
@Thigmotropism that's why I wrote my own answer in the first place.Roca
@JanDvorak I thought yours would be faster - it's good to have proof!Thigmotropism
This one works for me, the answer with a back-reference not.Orvie
R
27

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.

Roca answered 5/12, 2012 at 11:4 Comment(3)
what would be the regex expression?Hm
@Hm the same as yours. I assumed "abc" was just a placeholder for something else that you already knew how to match.Roca
Can you show this example on regex101? Does it also work with the python or php settings?Lest
I
5

You can also do this

yourString.replace(/([a-z]+)/ig, "#$1#")
Irrupt answered 5/12, 2012 at 11:12 Comment(2)
This replaces all occurances with #abC# which is not what I wantHm
@Hm you can remove g if you dont want to match all occurancesIrrupt

© 2022 - 2024 — McMap. All rights reserved.