TheDude
TheDude

Reputation: 3105

Replace *variable* text but keep case

I need to replace some text in a javascript variable without losing case, ie.

"MAT" ==> "MATch string in db" instead of "Mat" ==> "match string in db"

Right now I'm doing this (doesn't keep the original case):

var user_str = $("#user-input").val();
var db_match = db_match.replace(new RegExp(user_str, "ig") , '<span class="u b match">' + user_str + '</span>');

I found cases where people needed to replace static text, but in my case I need to replace variable content instead.

Obviously this doesn't work either:

var user_str = $("#user-input").val();
db_match = db_match.replace(/(user_str)/ig, "<span class=u b match>$1</span>");

Any idea how to do this?

Upvotes: 1

Views: 1342

Answers (1)

epascarello
epascarello

Reputation: 207557

Use a group and build the regular expression

    var str = "test";
    var text = "Test this";
    var re = new RegExp("(" + str + ")","gi");
    console.log(text.replace(re, "<span>$1</span>"))  //"<span>Test</span> this"

Upvotes: 9

Related Questions