3

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.

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

3 Comments

Wow, mad ups on your second example, didn't know the function took the subpatterns as parameters. THANK YOU SO MUCH
why doesn't it accept arrow function?
the code was written 15 years ago. You can use an arrow function, but you do not get "arguments" as an array. (match, p1, p2, /* …, */ pN, offset, string, groups) => replacement; the number "p" arguments depends on the number of matches your regex is capturing.
0

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.

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.