Wrap character in String, excluding a Link tag with Javascript Regex

前端 未结 3 1245
天命终不由人
天命终不由人 2021-01-28 08:54

EDIT

heres what i have to do...

Imagine if i have a text with some html tags inside it (it is still a string):

var string = \'

Hello, my

3条回答
  •  不要未来只要你来
    2021-01-28 09:24

    Does this solution matches your requirements?

    string = string.replace(/a(?![^<]*?>)/g, 'a');
    

    A little help about (?![^<]*?>) (roughly : "some text not followed by >") :

    (?!...)   not followed by
    [^<]*     any char except "<", zero or more times
    ?>        until next ">"
    

    Wrapped inside a function :

    function replace(html, text, replacement) {
        // RegExp.escape : http://stackoverflow.com/q/3561493/1636522
        var re = new RegExp('(' + RegExp.escape(text) + ')(?![^<]*?>)', 'g');
        return html.replace(re, replacement);
    }
    
    var html = ' azerty < azerty ';
    html = replace(html, 'azerty', '$1');
    // " azerty < azerty "
    

提交回复
热议问题