Jared
Jared

Reputation: 6060

JavaScript/jQuery case indifferent RegEx replace

I'm trying to figure out how to do a RegEx search on a string that ignores case, but when it does a replacement it should preserve the original case.

i.e.

Searching for "adv" should match "Adv", but the replacement should match "Adv" not "adv"

The purpose is to 'highlight' text in a string. Obviously if there is something easier I'm all ears.

Current code...

$("#SearchResults").append(appendString.replace(
    new RegExp($("#SearchInput").val(), "g"), "<strong>" + 
    $("#SearchInput").val() + "</strong>")
);

Upvotes: 0

Views: 116

Answers (2)

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

You need to encapsulate the value with parenthesis, this will create a group and you will be able the get that group in the replacement string with $n where n is the number of the group. The index start to 1.

So use that :

appendString.replace(new RegExp('(' + $("#SearchInput").val() + ')', "gi"), "<strong>$1</strong>");

Note that using regexp like that is dangerous, for instance, if I write (hello in the input, it will throw an error : invalid regexp.

Upvotes: 1

bvaughn
bvaughn

Reputation: 13487

Karl's approach is right, although you might also need to escape special characters:

var value = $("#SearchInput").val();
var escaped = value.replace(/([\[\]\(\)\/\.\*\+])/g, "\\$1");

// Regex: new RegExp(escaped, "gi");
// Replace with: "<strong>" + value + "</strong>");

Edit for typo.

Upvotes: 0

Related Questions