Replace text but keep case

I'll leave this here for reference.

Scenario: case-insensitive search box on list of items, partial match on string should be displayed highlighted but keeping original case.

highlight() {
  const re = new RegExp(this.searchValue, 'gi'); // global, insensitive
  const newText = name.replace(re, `<b>$&</b>`);
  return newText;
}

the $& is the matched text with case


Here’s a helper:

function matchCase(text, pattern) {
    var result = '';

    for(var i = 0; i < text.length; i++) {
        var c = text.charAt(i);
        var p = pattern.charCodeAt(i);

        if(p >= 65 && p < 65 + 26) {
            result += c.toUpperCase();
        } else {
            result += c.toLowerCase();
        }
    }

    return result;
}

Then you can just:

"oooAsdFoooo".replace(r, function(match) {
    return matchCase("qwer", match);
});

Tags:

Javascript