Javascript replace null

var p = "null" var q = null; (p == q) //false. as Expected. p.replace(null, "replaced") // outputs replaced. Not expected. p.replace("null", "replaced") //outputs replaced. Expected. q.replace(null, "replaced") // error. Expected. q.replace("null", "replaced") //error. Expected. 

Why? Does the difference between "null" and null replace?

I ask because I encountered an error in angularjs:

 replace((pctEncodeSpaces ? null : /%20/g), '+'); 

If, for example, someone had a username "null" and it was used as a url, it would be replaced with a "+" for any calls to $http . e.g. GET /user/null .

Not that this scenario happens often, but I'm more curious why replacing null and "null" calls is the same thing. Does ".tostring" replace with null before replacing? Is this just a javascript fad?

I checked this in both IE and Chrome replace versions.

+4
source share
4 answers

Yes, this is expected in accordance with the specification for replace (bold line or page 146 of the final draft ECMA-262 ). The first argument is checked to see if it is a regular expression, and if not, it calls toString() (well, one way or another).

15.5.4.11 String.prototype.replace(searchValue, replaceValue)

Let a string denote the result of converting this value to a string.

Short for short

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

Short for short

+4
source

In the ES5 specification for String.prototype.replace :

15.5.4.11 String.prototype.replace (searchValue, replaceValue)

...

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

So, "".replace(null, XXX) really converts null to the string "null"

Note that ToString() does not mean null.toString() is an internal specific operation in the JavaScript interpreter.

+3
source

For not expected, there is a simple answer. Zero is passed to the string by the replace () method.
So this is also an expected action.

0
source
 "null".replace(null, "replaced") // outputs replaced. Not expected. 

Does the difference between null and null replace

This is because parameter 1 from replace converted to String.

 ''+null === "null"; // true by cast to string 

Also, since replace accepts RegExp objects, you might also think about how

 RegExp(null).toString() === "/null/"; // true 
-1
source

All Articles