0

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);

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

aww, my simple solution just eval'd match... but I was ashamed to post it. gist.github.com/rlemon/234f1e262089cd5fc7d4
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.