2

Let's say I have this string:

<i id="1"></i><i id="2"></i><i id="3"></i>

and this object:

{
  "1": "Red",
  "2": "Green",
  "3": "Blue"
}

Then I want to obtain this string:

<i color="Red"></i><i color="Green"></i><i color="Blue"></i>

Would be possible to make it through a regex replace?

I've tried this:

var stringIwant = stringIhave.replace(/id="(\d)"/g, 'color="' + myObject["$1"] + '"')

But it tries to read the property "$1" of the object, which doesn't exist. I also tried removing the quotes around $1:

var stringIwant = stringIhave.replace(/id="(\d)"/g, 'color="' + myObject[$1] + '"')

But I obtain a ReferenceError: $1 is not defined

I've tried more things, but nothing worth mentioning.

That's why I wonder if this is even possible. Any help?

2
  • 1
    Note that "color" is not a standard attribute for the HTML <i> tag, though you can use it for your own purposes. Commented Aug 5, 2018 at 13:17
  • 1
    Don't worry, it's an example I created to expose my problem Commented Aug 5, 2018 at 13:25

2 Answers 2

5

You can do that with callbacks:

const stringIhave = `<i id="1"></i><i id="2"></i><i id="3"></i>`;

const obj = {
  "1": "Red",
  "2": "Green",
  "3": "Blue"
};

const stringIwant = stringIhave.replace(/id="(\d)"/g, (mat, grp) => `color="${obj[grp]}"`
);

console.log(stringIwant);

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

Comments

2

You can take advantage of the fact that .replace() can be passed a function as the second parameter:

var stringIWant = stringIHave.replace(/id="(\d)"/g, function(wholeMatch, digits) {
  return "color='" + myObject[digits] + "'";
};

The first argument to such a function will be the entire match. The second and subsequent arguments will be the ( ) groups from your regex (if any). The returned value is used as the replacement for the entire match. When the regex has the "g" flag (as in your case), the function will be called on each match iteration.

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.