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

前端 未结 3 1262
野性不改
野性不改 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:36

    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/

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-01 06:46

    You can also do this

    yourString.replace(/([a-z]+)/ig, "#$1#")
    
    0 讨论(0)
提交回复
热议问题