Franco Caruso
Franco Caruso

Reputation: 3

Javascript Replace with variable in string with Regular Expression

I want to replace a lot of keywords in string with pre-defined variables, samples as below, but now $1 only shows variable name, not variable content, any one can help me, please!!!

Correct:

1111{t:aa}
2222{t:bb}
3333{t:cc}

To:

1111Test1
2222Test2
3333Test3

Not:

1111aa
2222bb
3333cc

Code:

var aa = "Test1";
var bb = "Test2";
var cc = "Test3";
var str_before = "1111{t:aa}\n2222{t:bb}\n3333{t:cc}";
var str_after = str_before.replace(/\{t:\s*(\w+)\}/g, "$1");
alert(str_before+"\n\n"+str_after);

Upvotes: 0

Views: 152

Answers (2)

codebytom
codebytom

Reputation: 448

There is a NPM package out there for this, it allows you to pass in the string, and an array of variables you want to replace them with. Find a simple example along with the link to the package below:

Example:

var str = "This is a {0} string for {1}"
var newStr = stringInject(str, ["test", "stringInject"]);

// This is a test string for stringInject 

NPM / GitHub links:

https://www.npmjs.com/package/stringinject

https://github.com/tjcafferkey/stringinject

Upvotes: 0

Alnitak
Alnitak

Reputation: 339786

A regexp constant (i.e. /.../ syntax) cannot directly refer to a variable.

An alternate solution would be to use the .replace function's callback parameter:

var map = {
    aa: 'Test1',
    bb: 'Test2',
    cc: 'Test3'
};

var str_before = "1111{t:aa}\n2222{t:bb}\n3333{t:cc}";
var str_after = str_before.replace(/{t:(\w+)}/g, function(match, p1) {
    return map.hasOwnProperty(p1) ? map[p1] : '';
});

This further has the advantage that your mapping from name to value is now easily configurable, without requiring a separately declared variable for each one.

Upvotes: 2

Related Questions