简体   繁体   中英

JavaScript RegEx Ignore String

I have search results returned from the server and a regex that highlights the result using words in the search query.

words = searchQuery.split(' ');

$.each(words, function() { 

  var word = this.trim();
  var regex = new RegExp('(' + word + ')(?!>|b>)', 'gi');

  searchResult = searchResult.replace(regex, "<b>$1</b>");

});

This works fine, until I search something like this:

Search term: "script with javascript"

Search result: "java script is a programming language..."

It should highlight the whole word like " javascript is a programming language...". However, since the string has changed from "javascript" to "java <b> script </b> ", it no longer matches the second word in the search query. It also produces weird values when the value of word is "b", "/", "<" or ">".

My question is how I can ignore the <b> and </b> tags in the regex and match only the original search query? i tried using lookahead, but it didn't work.

I think descending sorting the array by string length can solve this issue:

words = searchQuery.split(' ');

words.sort(function(a, b){
  return b.length - a.length;
});

$.each(words, function() { 

  var word = this.trim();
  var regex = new RegExp('(' + word + ')(?!>|b>)', 'gi');

  searchResult = searchResult.replace(regex, "<b>$1</b>");

});

You cannot ignore anything inside a string by regex. Try to search whole words by use "\\b"

 var searchQuery = 'script with lang javascript'; var searchResult = 'javascript is a programming language'; words = searchQuery.split(' '); $.each(words, function() { var word = this.trim(); var regex = new RegExp('\\\\b(' + word + ')\\\\b(?!>|b>)', 'gi'); searchResult = searchResult.replace(regex, "<b>$1</b>"); }); console.log(searchResult); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 

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