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
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
xand 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 predefinedRegExpobject'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'));
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.
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.