JavaScript String replace - How do you use matched variables in the replacement string?

后端 未结 2 1113
误落风尘
误落风尘 2020-12-16 18:03

How do you use the matched variables in the pattern in the replacement string?

var regexp = new RegExp(\'needle\', \'ig\');
str.replace(regexp, \'

        
相关标签:
2条回答
  • 2020-12-16 18:27

    The correct way to use backreferences in JavaScript is via $1...$9.

    To make your example work:

    var regexp = new RegExp(something, 'ig');
    var result = str.replace(regexp, '<span class="marked">$1</span>');
    

    More information is available here: http://www.regular-expressions.info/javascript.html#replace

    0 讨论(0)
  • 2020-12-16 18:42

    try

    var regexp = new RegExp(something, 'ig');
    str.replace(regexp, '<span class="marked">$&</span>')
    

    References:

    • A table specifying the format of different tokens to be used into the replacement string

    • An example on how to switch two words into a string

    0 讨论(0)
提交回复
热议问题