简体   繁体   中英

JavaScript RegExp - How to match a word based on conditions

I'm building a search results page (in Angular) but using regular expressions to highlight the searched 'keywords' based on a condition. I'm having problems with RegExp with getting the correct condition, so apologies if my current syntax is messy, I've been playing about for hours.

Basically for this test i'm highlighting the word 'midlands' and I want to highlight every 'midlands' word except the word within the 'a' tag <a /> of the href="" attribute. So anything that's apart of the URL I do not want to highlight as I'll be wrapping the keywords within a span and this will break the url structure. Can anyone help? - I think I'm almost there.

Here's the current RegExp I'm using:

/(\b|^|)(\s|\()midlands(\b|$)(|\))/gi

Here's a link to test what I'm after. https://regex101.com/r/wV4gC3/2

Further info, after the view has rendered I grab the the html content of the repeating results and then do a search based on the rendered html with the condition above. - If this helps anyone.

You're going about this all wrong. Don't parse HTML with regular expressions - use the DOM's built in HTML parser and explicitly run the regex on text nodes .

First we get all the text nodes. With jQuery that's:

var texts = $(elem).content().get().filter(function(el){
    return el.nodeType === 3; // 3 is text
});

Otherwise - see the answer here for code for getting all text nodes in VanillaJS.

Then, iterate them and replace the relevant text only in the text nodes:

foreach(var text of texts) { // if old browser - angular.forEach(texts, fn(text)
    text.textContent = text.textContent.replace(/midlands/g, function(m){
       return "<b>" + m + "</b>";  // surround with bs. 
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM