1

Below is my code for string replacing:

var input = "player @renish Score";
var matches = input.replace(/@\w*/g,'$1 55');

The output is

player $1 55 Score

I want the output like

player @renish 55 Score

3 Answers 3

2

The $1 is called a backreference and it will be valid only if there is a valid capturing group.

Quoting MDN's Grouping and back references section,

(x)

Matches x and remembers the match. These are called capturing parentheses.

For example, /(foo)/ matches and remembers "foo" in "foo bar". The matched substring can be recalled from the resulting array's elements [1], ..., [n] or from the predefined RegExp object's properties $1, ..., $9. You need to introduce a capturing group, like this

console.log(input.replace(/(@\w*)/g,'$1 55'));

Now, we capture the string @\w*, and the $1 will represent the captured string.


Alternatively, as per the ECMA Script 5.1 Specification for String.prototype.replace, you can use $& to represent the matched string.

$&

The matched substring.

So, you can use the code as it is and simply change the replacement pattern to $&, like this

console.log(input.replace(/@\w*/g,'$& 55'));
Sign up to request clarification or add additional context in comments.

Comments

1

You'll need to specify what part of your regex is your capturing group, using ():

var input = "player @renish Score";
var matches = input.replace(/(@\w*)/g,'$1 55');
alert(matches)

Otherwise, the replace will literally place "$1" into your string, because you haven't specified a capturing group.

Comments

1

You need to reference the whole match with $& , no need in capturing groups:

var input = "player @renish Score";
alert(input.replace(/@\w*/g,'$& 55'));

See MDN reference:

$&    Inserts the matched substring.

Mind that adding capturing groups should only be performed when you only need to refer to some subpattern. Additional capturing groups mean additional overhead.

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.