0

I'm making a script that highlights a part of a string by wrapping it in a span. (the part that is highlighted is decided via a form)

Right now I've got this.

value.replace(term,'<span>'+term+'</span>')

$(document).ready(function(){
  var term = $('.n').val();
  var matches = ['Tree of life','Life of the tree'];
  $('.output>div').remove();
    $.each(matches,function(index,value){
        $('.output').append('<div>'+value.replace(term,'<b>'+term+'</b>')+'</div>')
    })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input type="text" class="n" value="Tree">

<h4>Output</h4>
<div class="output">
</div>

But thing is, this needs the term to be the same capitalization.

So if I'm searching for Tree:

  • Tree of life -> has a match
  • Life of the tree -> doesn't have a match

So how can I do a replace in JS, but that doesn't take in account the capitalization?

Fredy31
  • 2,251
  • 6
  • 23
  • 46

1 Answers1

0

Turn the first argument to replace into a case-insensitive regular expression, rather than just a string:

// https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
const escape = s => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
const pattern = new RegExp(escape(term), 'i');
const result = value.replace(pattern, '<span>'+term+'</span>');

If you want to replace all occurrences, use the g flag as well.

CertainPerformance
  • 260,466
  • 31
  • 181
  • 209