Doug
Doug

Reputation: 869

Using Regex Subpatterns in Object Keys (using .replace())

I have a question about the way .replace() works

I know that we can use subpatterns within the replace text like this

var somestr="foobar";
var newstr = somestr.replace(/foo([a-zA-Z]*)/g,"bar$1")
alert(newstr) //"barbar"

However, I am wondering if it is even possible to use the subpattern in an object property, like this.

var somestr = "foobar";
var someobj = {bar:'fuu',two:'uuf'}

var newstr = somestr.replace(/foo([a-zA-Z]*)/g, someobj["$1"])

alert(newstr) //"fuu" ?

My expected result would have been to get the 'bar' property of someobj, which would be "fuu", however the actual result is undefined, which would lead me to believe this is impossible.

How could I otherwise accomplish similar functionality? Perhaps one of you JS gurus could shed some light on this.

The real-world purpose behind this is I have a template system that uses shorttags to display pieces of data from a requested JSON object, who's code I am attempting to streamline.

Upvotes: 3

Views: 1466

Answers (2)

nickytonline
nickytonline

Reputation: 6981

You can do this:

var someString = "foobar";
var someObject= {bar:'fuu',two:'uuf'};
var re = /foo([a-zA-Z]*)/g;

if (re.test(someString)) {
    alert(someObject[RegExp.$1]);
}

See the fiddle here, http://jsfiddle.net/nickyt/AjjjP

You could also just do this alert(someObject[someString.replace(/foo([a-zA-Z]*)/g, "$1")]); but the problem with this is, if nothing is found in $1, your object looks for am empty string key. I would stick with what I have above.

Upvotes: 0

Joe
Joe

Reputation: 82634

Not like this, I added $1 to show the fail:

var somestr = "foobar";
var someobj = {bar:'fuu',two:'uuf', $1: 'test'}

var newstr = somestr.replace(/foo([a-zA-Z]*)/g, someobj["$1"])

newstr; // "test";

but this would work:

var somestr = "foobar";
var someobj = {bar:'fuu',two:'uuf', $1: 'test'}

var newstr = somestr.replace(/foo([a-zA-Z]*)/g, "$1")

someobj[newstr]; // fuu

or maybe better yet, replace takes a function:

var somestr = "foobar";
var someobj = {bar:'fuu',two:'uuf', $1: 'test'}

var newstr = somestr.replace(/foo([a-zA-Z]*)/g, function () {
    return someobj[arguments[1]];
})

newstr; // fuu

Upvotes: 4

Related Questions