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
.
Null Values can be replaced in SQL by using UPDATE, SET, and WHERE to search a column in a table for nulls and replace them. In the example above it replaces them with 0. Cleaning data is important for analytics because messy data can lead to incorrect analysis.
There are two ways to replace NULL with blank values in SQL Server, function ISNULL(), and COALESCE(). Both functions replace the value you provide when the argument is NULL like ISNULL(column, '') will return empty String if the column value is NULL.
In JavaScript, == compares values by performing type conversion. Both null and undefined return false. Hence, null and undefined are considered equal.
null is a special value in JavaScript that represents a missing object. The strict equality operator determines whether a variable is null: variable === null . typoef operator is useful to determine the type of a variable (number, string, boolean).
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, letsearchString
beToString(searchValue)
and search string for the first occurrence ofsearchString
. Let m be 0.Cut for brevity
In the ES5 specification for String.prototype.replace
:
15.5.4.11 String.prototype.replace (searchValue, replaceValue)
...
If
searchValue
is not a regular expression, letsearchString
beToString(searchValue)
and searchstring
for the first occurrence ofsearchString
So, "".replace(null, XXX)
will indeed convert the null
to the string "null"
Note that ToString()
does not mean null.toString()
- it's an internal defined operation within the JavaScript interpreter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With