JavaScript - string regex backreferences

后端 未结 5 1688
抹茶落季
抹茶落季 2020-11-27 02:51

You can backreference like this in JavaScript:

var str = \"123 $test 123\";
str = str.replace(/(\\$)([a-z]+)/gi, \"$2\");

This would (quite

5条回答
  •  感动是毒
    2020-11-27 03:51

    Note: Previous answer was missing some code. It's now fixed + example.


    I needed something a bit more flexible for a regex replace to decode the unicode in my incoming JSON data:

    var text = "some string with an encoded 's' in it";
    
    text.replace(/&#(\d+);/g, function() {
      return String.fromCharCode(arguments[1]);
    });
    
    // "some string with an encoded 's' in it"
    

提交回复
热议问题