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

前端 未结 3 1261
野性不改
野性不改 2021-02-01 05:50

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.

3条回答
  •  不思量自难忘°
    2021-02-01 06:43

    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.

提交回复
热议问题