Javascript Regex: How to bold specific words with regex?

前端 未结 4 1663
礼貌的吻别
礼貌的吻别 2020-12-10 05:56

Given a needle and a haystack... I want to put bold tags around the needle. So what regex expression would I use with replace()? I want SPACE to be the delimeter and I want

4条回答
  •  萌比男神i
    2020-12-10 06:08

    Here is a regex to do what you're looking for:

    (^|\s)(cows)(\s|$)
    

    In JS, replacement is like so:

    myString.replace(/(^|\s)(cows)(\s|$)/ig, '$1$2$3');
    

    Wrapped up neatly in a reusable function:

    function updateHaystack(input, needle) {
        return input.replace(new RegExp('(^|\\s)(' + needle + ')(\\s|$)','ig'), '$1$2$3');
    }
    
    var markup = document.getElementById('somediv').innerHTML;
    var output = updateHaystack(markup, 'cows');
    document.getElementById('somediv').innerHTML = output;
    

提交回复
热议问题