Thursday, March 21, 2019

Case-insensitive matching with case-sensitive replacements in JavaScript

That title is a mouth full. Here is what I was trying to accomplish: I had a search term that I wanted to highlight in a body of text. So my code needed to match all occurrences of the search term and then enclose the matched text within some HTML in order to format it. Seems simple enough, but I ran into a couple of issues.

Let's say I am going to format a phone number from a string of digits. I would do it like this:
let phone = '5551234567';
phone = phone.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
But that syntax doesn't work for me here because I need to pass the search pattern as a variable name and I need to specify the "i" and "g" flags. So this code will not work:
const searchTerm = 'xyz';
myText = myText.replace(/searchTerm/ig, 'THE'); // Not valid
First, I use the RegExp constructor to define my pattern.
const searchTerm = 'xyz';
const pattern = RegExp(searchTerm, 'ig');
let myText = 'xyz XYZ xYz';
myText = myText.replace(pattern, 
  `<span class='highlight'>${searchTerm}</span>); 
  // Results will all be lowercase because searchTerm is lowercase
Then I had to create an array of matches that I could then loop through and replace each one individually:
let sampleText = 'This is my sample text: test Test TEST';
const searchText = 'test';
const pattern = new RegExp(searchText, 'ig');
const matches = sampleText.match(pattern, sampleText);
if (matches !== null) {
 matches.forEach((match) => {
  sampleText = sampleText.replace(match, `${match}`);
 });
}
To see this in action, take a look at this JSFiddle.
 
Blogger Templates