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

前端 未结 3 1314
野性不改
野性不改 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/

提交回复
热议问题