1

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: "javascript 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.

1
  • 3
    Simply sort search terms by string length before highlighting. Commented Mar 15, 2015 at 20:50

2 Answers 2

1

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>");

});
Sign up to request clarification or add additional context in comments.

2 Comments

hmm. this actually works. but is there any way to ignore the "<b>" and "</b>" in the regex? that would make things a lot easier
@ameernuri: Have a look at the similar issue - stackoverflow.com/a/28991840/3832970, though I do not know if you can modify a search query that much (e.g. if you allow a regex expression in it).
0

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>

2 Comments

but the word may not be a boundary. just like script in javascript!
@ameernuri give me an example with problem, plz

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.