Javascript replace null
javascript
Solution
Yes, this is expected according to the spec for `replace` (bolded relevant line, or page 146 of the ECMA-262 final draft). The first argument is checked to see if it is a regex and if not, it has `toString()` called on it (well, converted to a string somehow).
15.5.4.11 `String.prototype.replace(searchValue, replaceValue)`
Let string denote the result of converting the this value to a string.
Cut for brevity
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.
Cut for brevity
Problem
``` 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 replace not differentiate between `"null"` and `null`? I ask because I ran into a bug in angularjs: ``` replace((pctEncodeSpaces ? null : /%20/g), '+'); ``` If for example, someone had a username of `"null"` and it was used as url, it would be replaced with "+" on any `$http` calls. e.g. `GET /user/null`. Not that this scenario would occur often, but I'm more curious why replace treats `null` and `"null"` as the same thing. Does replace do a .tostring on `null` before it does the replacement? Is this just a quirk of Javascript? I verified this on both IE and Chrome's implementations of `replace`.