Is it possible to coerce captured values into numbers from within replace() in JavaScript?
If I were to replace all occurrences of {n}
in a string with the captured value, like so:
"Replacing {1} multiple {2} occurrences.".replace(/\{(\d)\}/g, "$1")
The result would correctly be:
Replacing 1 multiple 2 occurrences.
Additionally, if I were to check the typeof
replacement "$1"
:
"Replacing {1} multiple {2} occurrences.".replace(/\{(\开发者_Python百科d)\}/g, typeof "$1")
I would get the expected result:
Replacing string multiple string occurrences.
What I Would Like To Do:
However, what I would like to do is use the captured values as array indexes and to do that, I would like to coerce the captured values into numbers with parseInt
, like so:
"Replacing {1} multiple {2} occurrences.".replace(/\{(\d)\}/g, parseInt("$1"))
Unfortunately, this returns:
Replacing NaN multiple NaN occurrences.
My Question:
Why am I unable to coerce these captured values into numbers?
"Replacing {1} multiple {2} occurrences.".replace(
/\{(\d+)\}/g, function (_, x) { return myArray[+x]; })
If the second argument to myString.replace
is a function then, for each match, it is called with the matching string ($&
) as its first argument, and any capturing groups as the subsequent arguments and its return value is coerced to a String and used as the replacement text.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace says
Specifying a function as a parameter
You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. (Note: the above-mentioned special replacement patterns do not apply in this case.) Note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.
In
Replacing string multiple string occurrences
string
is not typeof 1
, but typeof "$1"
(the literal string "$1"
).
That's what may be confusing you. In the same manner, you are trying to evaluate parseInt("$1")
, and the result is (correctly) NaN
.
精彩评论