Javascript replace null

Javascript replace null

本文关键字:null replace Javascript      更新时间:2023-09-26
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.

为什么?替换不区分"null"null吗?

我问这个问题是因为我在angularjs中遇到了一个bug:

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

例如,如果有人有"null"的用户名,它被用作url,它将在任何$http调用上被替换为"+"。例:GET /user/null;

并不是说这种情况会经常发生,但我更好奇的是为什么replace将null"null"视为同一件事。替换在null上做一个。tostring替换之前?这只是Javascript的一个怪癖吗?

我在IE和Chrome的replace实现上验证了这一点。

是的,根据 replace 的规范(加粗的相关行,或ECMA-262最终草案 第146页),这是预期的。检查第一个参数是否为正则表达式,如果不是,则调用toString()(好吧,以某种方式转换为字符串)。

15.5.4.11 String.prototype.replace(searchValue, replaceValue)

让string表示将this值转换为字符串的结果。

剪短

如果searchValue不是正则表达式,searchStringToString(searchValue) ,并查找第一次出现的字符串searchString。设m为0

剪短

在ES5规范中对于String.prototype.replace:

15.5.4.11 String.prototype.replace (searchValue, replaceValue)

如果 searchValue 不是正则表达式,则令 searchString ToString(searchValue) ,并在 string 中查找第一次出现的 searchString

因此,"".replace(null, XXX)确实会将null转换为字符串"null"

注意,ToString()不是表示null.toString()——它是JavaScript解释器内部定义的操作。

对于意料之外的问题,有一个简单的答案。null被replace()方法转换为字符串。
这也是一个预期动作

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

不区分"null"answers"null"

这是因为replace参数1被转换为String

''+null === "null"; // true by cast to string
此外,由于replace接受RegExp对象,您还可以考虑如何
RegExp(null).toString() === "/null/"; // true