JavaScript regex - How to wrap matches with tag?

前端 未结 4 1204
走了就别回头了
走了就别回头了 2020-12-02 00:35

I have a string in JavaScript in which I\'d like to find all matches of a given phrase and wrap them with a tag. I haven\'t been able to find the right regex method here to

4条回答
  •  孤街浪徒
    2020-12-02 00:56

    One needs no capturing group around the whole regex because there is a $& placeholder that refers to the whole match from the string replacement pattern:

    "Foo bar cat".replace(/cat/ig, "$&");
                                        ^^
    

    See the Specifying a string as a parameter section:

    $&    Inserts the matched substring.

    Thus, no need of any callback methods or redundant regex constructs.

提交回复
热议问题