Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
47
rated 0 times [  51] [ 4]  / answers: 1 / hits: 23521  / 11 Years ago, tue, april 30, 2013, 12:00:00
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.


More From » javascript

 Answers
24

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



IfsearchValue 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



[#78504] Monday, April 29, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brooksb

Total Points: 480
Total Questions: 98
Total Answers: 106

Location: Somalia
Member since Mon, Feb 27, 2023
1 Year ago
;