JavaScript String Replace with regular expression and function as arguments

后端 未结 2 440
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-08 14:52

I seem to be getting conflicting advice in the books I read on this functionality. I\'m wondering if someone could clarify. For example Nicholas Zakas states the function argume

相关标签:
2条回答
  • 2021-02-08 15:28

    The ECMAScript spec has:

    String.prototype.replace (searchValue, replaceValue)
    

    If searchValue is a regular expression (an object whose [[Class]] property is "RegExp"), do the following: If searchValue. global is false, then search string for the first match of the regular expression searchValue. If searchValue.global is true, then search string for all matches of the regular expression searchValue. Do the search in the same manner as in String.prototype.match, including the update of searchValue. lastIndex. Let m be the number of left capturing parentheses in searchValue (NCapturingParens as specified in 15.10.2.1).

    If searchValue is not a regular expression, let searchString be ToString(searchValue) and search string for the first occurrence of searchString. Let m be 0.

    If replaceValue is a function, then for each matched substring, call the function with the following m + 3 arguments. Argument 1 is the substring that matched. If searchValue is a regular expression, the next m arguments are all of the captures in the MatchResult (see 15.10.2.1). Argument m + 2 is the offset within string where the match occurred, and argument m + 3 is string. The result is a string value derived from the original input by replacing each matched substring with the corresponding return value of the function call, converted to a string if need be.

    It's a bit confusing but I think Zakas is right.

    0 讨论(0)
  • 2021-02-08 15:30

    Zakas is correct, the penultimate and final arguments are pos and originalText. From the ECMA-262 3rd and 5th editions (section 15.5.4.11):

    If replaceValue is a function, then for each matched substring, call the function with the following m + 3 arguments. Argument 1 is the substring that matched. If searchValue is a regular expression, the next m arguments are all of the captures in the MatchResult (see 15.10.2.1). Argument m + 2 is the offset within string where the match occurred, and argument m + 3 is string.

    Note that String.prototype.replace was new in ECMA-262 3rd edition. MSDN documentation for JScript and MDC documentation for JavaScript both conform to this specification.

    • replace Method (Windows Scripting - JScript)
    • replace - MDC
    0 讨论(0)
提交回复
热议问题