JavaScript regex - How to wrap matches with tag?

前端 未结 4 1189
走了就别回头了
走了就别回头了 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:45

    You can solve it very simple, just use a capturing group with the word you want, and then use the replacement string <em>$1</em>. You can use a regex like this:

    (cat)
    

    working demo

    Below, you can see in green the matches (capturing the word cat insensitively) and in the substitution section you can see the replacements.

    enter image description here

    You can use this code:

    var re = /(cat)/ig; 
    var str = '"I like to play with cats, as does Cathy, who is a member of ACATA, which is the American Cat And Tiger Association."\n';
    var subst = '<em>$1</em>'; 
    
    var result = str.replace(re, subst);
    
    0 讨论(0)
  • 2020-12-02 00:49

    You could use:

    "Foo bar cat".replace(/(cat)/ig, "<em>$1</em>");
    

    Which will return:

    "Foo bar <em>cat</em>"
    
    0 讨论(0)
  • 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, "<em>$&</em>");
                                        ^^
    

    See the Specifying a string as a parameter section:

    $&    Inserts the matched substring.

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

    0 讨论(0)
  • 2020-12-02 01:04

    You can do straight-up replace by using a replace function:

    str.replace(/cat/ig, function replace(match) { 
        return '<em>' + match + '</em>'; 
    });
    
    0 讨论(0)
提交回复
热议问题