1

I have:

 window.page="home";
 document.getElementsByTagName("title")[0].innerHTML=
      "hello.com | $page".replace(/\$([^\s]*)/g,window["$1"]);

The idea is to get:

 <title>hello.com | home</title>

But I instead get:

 <title>hello.com | undefined</title>

When I do the following:

 document.getElementsByTagName("title")[0].innerHTML=
      "hello.com | $page".replace(/\$([^\s]*)/g,"$1");

I get:

 <title>hello.com | page</title>

This is because the function is taking "$1" as an argument with which to map its output. I'm wondering if there is a way to use the capture group to access an array/object?

2
  • 1
    Use a callback, .replace(/\$(\S*)/g, function($0,$1) {return window[$1];}) Commented Jul 23, 2017 at 21:44
  • Thanks. I can't believe I didn't think to do that. Commented Jul 23, 2017 at 21:45

1 Answer 1

1

You cannot use a backreference that can only be used a part of the string replacement pattern as an argument. You need to use a replace callback for that.

Use

.replace(/\$(\S*)/g, function($0,$1) {return window[$1];})

Note that \S (a non-whitespace) is shorter than [^\s] (not a whitespace).

In function($0,$1), the $0 stands for the whole match, while $1 stands for the Group 1 contents.

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

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.