Iulian Onofrei
Iulian Onofrei

Reputation: 9730

Javascript regex match different groups

I want to replace different parts of a string with a word that's inside of every matching group. So, if I have this string:

<td>{$phrase->getId()}</td>
<td>{$phrase['name']}</td>
<td>{$phrase['id']}</td>

I would like to be able to get the string:

<td>id</td>
<td>name</td>
<td>id</td>

I tried this expression:

\{\$\w+(?:\['(\w+)'\]|->get(\w+)\(\))\}

but when I input.replace(regex, "$1") I get:

<td></td>
<td>name</td>
<td>id</td>

Upvotes: 2

Views: 55

Answers (1)

aelor
aelor

Reputation: 11116

replace with $1$2 since you have used | or operator

like this : input.replace(regex, "$1$2");

for the first sentence the Id is coming inside the second capture group, thus it is not matching the first one.

Upvotes: 3

Related Questions