-1

I am using jQuery to find text in an html and highlight all occurrences of a text, replacing them for a span tag.

<div>This a sample paragraph. Sample is it?</div>

I am using the following piece of code to replace all occurrence of a word

var $test = $('div').html();

$test = $test.replace( new RegExp('sample',"g"), '<span class="hilite">sample</span>'

I would like to change all occurences of sample doesn't matter how it is written [Sample, SAMPLE, samplE] I would like to highlight the intended word, how could I do it?

freedomn-m
  • 27,664
  • 8
  • 35
  • 57
Diego Rueda
  • 2,226
  • 4
  • 21
  • 41
  • Please don't edit the question. Both existing answers are valid answers for the original question. Anyone looking at your question *now* will see answers that don't match the question. Are new answers more valid that the original answers? How will you mark the *correct* answer? The first, correct answer, or a new one that doesn't answer the original question but now answers the edit? Please create a new question (link to this one if desired). – freedomn-m Jan 25 '17 at 17:06
  • Worse, the existing, correct answer now looks like it's just a copy of the code in your question and will likely elicit *downvotes*. – freedomn-m Jan 25 '17 at 17:09
  • Restored the original question. – freedomn-m Jan 25 '17 at 17:10
  • ok i got it, should i create a new question or edit this one with more details? – Diego Rueda Jan 25 '17 at 17:22
  • Yes, you can add more details for clarification (especially when questions are asked in the comments), as long as the overall question doesn't change - otherwise create a new question. – freedomn-m Jan 25 '17 at 17:35
  • Did you tried [mark.js](https://markjs.io/)? – dude Jan 25 '17 at 19:08

2 Answers2

2
$test = $test.replace(new RegExp('sample', "gi"), '<span class="hilite">sample</span>');

Use the i flag for insensitive.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

freedomn-m
  • 27,664
  • 8
  • 35
  • 57
Paul
  • 1,527
  • 2
  • 16
  • 24
1

Add the toLowerCase() function when you search for the word, like this:

var $test = $('div').html().toLowerCase();

Link

RonyLoud
  • 2,408
  • 2
  • 20
  • 25
Dwadelfri
  • 454
  • 1
  • 4
  • 15
  • I like this suggestion as well. You can use the toLowerCase() which would make the need for RegEx unnecessary. Not too sure how much faster computationally it would be. But it would be an interesting study. – Paul Jan 25 '17 at 16:43