mark text in a string with regular expression but exclude links

I have a text and I want when a user search for a term, the term becomes highlighted by wrapping the term with mark tag.

javascript to wrap the match term:

var sampleText = window.document.getElementById('test').innerHTML;
var _keywordHighlight = function (text, term) {
  var pattern = new RegExp('('+term+')', 'gi');
  text = text.replace(pattern, '<mark>$1</mark>');;
  return text;
};

var newText = _keywordHighlight(sampleText, 'sample');
window.document.getElementById('test').innerHTML = newText;

jsfiddle.net link:

https://jsfiddle.net/homa/j0Lgk6pf/

The problem is, the search term inside the url also wraps by mark tag and it broke the link.

How can I exclude links to be wrapped by mark tag?

Answers:

Answer

Use a negative lookahead to add an additional constraint that the term is not followed by a > without first having a <. This will effectively exclude matches within <...> markup.

var pattern = new RegExp('('+term+')(?![^<]*>)', 'gi');

https://jsfiddle.net/qdk80o0k/

Answer
  1. You're reinverting the wheel
  2. Using innerHTML will destroy events
  3. Using innerHTML will trigger regeneration of the DOM

To make thins easy you should use an existing plugin. There are many jQuery plugins out there, but as you haven't added the jquery tag I assume that you're searching a plain JS solution. Then the only plugin is mark.js.

Example of your use case

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.