fanfavorite
fanfavorite

Reputation: 5199

Regex first result ($1) replacement as property of variable

I am trying to find all instances starting with '%%msgStrs.' and ending with '%%' in a string and replace with that actual variable msgStrs['whatever']. Here is some sample code:

var msgStrs = {
    test: "1",
    test2: "2"
}

var msg = 'Test %%msgStrs.test%% test2 %%msgStrs.test2%%';
msg = msg.replace(/%%msgStrs\.(.*?)%%/g,msgStrs['$1']);

Here is the fiddle.

The regex seems to be working and $1 is returning the right one, but it must be in the wrong type format as the msgStrs variable shows undefined. If I change the replace line to:

msg = msg.replace(/%%msgStrs\.(.*?)%%/g,"msgStrs['$1']");

This will show the correct string for $1.

Why won't it pull msgStrs.test and msgStrs.test2?

Upvotes: 2

Views: 36

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626870

You need to perform this inside a callback:

var msgStrs = {
    test: "1",
    test2: "2"
}

var msg = 'Test %%msgStrs.test%% test2 %%msgStrs.test2%%';
msg = msg.replace(/%%msgStrs\.(.*?)%%/g, function(match, group1) {
   return msgStrs[group1] ? msgStrs[group1] : match;
});

console.log(msg); // => Test 1 test2 2

Where m is the whole match and g is the captured submatch. If there is no value for the currently matched g, the whole match is returned (due to msgStrs[g] ? msgStrs[g] : m;).

Upvotes: 1

Related Questions