当replace遇到$美元符号引发的问题和解决方案
今天测试同时提了一个bug,页面显示错乱。 因为是线上的问题,用ie8查看出的js是混淆过的。 于是,先用fidder把autoResponse设置成本地的一个没有加密混淆过的js文件。 定位到问题是出现在 “str = str.replace(/b/g,data.info);”这一行。
查看下data.info,打印出来的内容是”m$_n”. str原始内容为”abc”, 预期结果是:”am$_nc”
var content="m$_n";
var str = "abc";
var res = str.replace(/b/g,content);
alert(res); //amabcnc
如果要使得content中的$无效,要把$替换成$$.
但结果是”amabcnc”. (内容本来为html代码,这里webryan给替换成便于理解的字符串). 对比不难发现$_被解释成了str本身的字符串”abc”(都是美元符号搞得鬼啊)。
查看了下javascript手册,发现还是学艺不精。 解释如下:
24.171.2. Description
replace( ) performs a search-and-replace operation on string. It searches string for one or more substrings that match regexp and replaces them with replacement. If regexp has the global “g” attribute specified, replace( ) replaces all matching substrings. Otherwise, it replaces only the first matching substring.
replacement may be a string or a function. If it is a string, each match is replaced by the string. Note that the $ character has special meaning within the replacement string. As shown in the following table, it indicates that a string derived from the pattern match is used in the replacement.
Replacement
$1, $2, …, $99: The text that matched the 1st through 99th parenthesized subexpression within regexp
$&: The substring that matched regexp
$’: The text to the left of the matched substring
$’: The text to the right of the matched substring
$$: A literal dollar sign
$_: The whole string //add by webryan
看到上述描述,对于javascript中的replace(exp,replacement)函数的replacement参数,$(美元符号)是有特殊含义的。 那么我们的replacement如果是服务器返回的内容或者是其他不可预知的字符串(可能包含$),最后的替换结果就会出问题。
那么如何规避这个问题呢? $$: A literal dollar sign –这个一行提示给了我们答案。 就是在replacement中$$是代表$符号的,也就是类似转义符一样。
那么我们程序可以改成如下:
var content="m$_n";
var str = "abc";
var res = str.replace(/b/g,content.replace(/\$/g,"$$$$"));
alert(res); //am$_nc
解释:因为content是”m$_4″,我们要把其中的$-美元符号合法化,就要把content中的$替换成$$。但是在replacement中$$才被当作一个$.所以我们把$替换成”$$$$”就好。
但是$在exp中也有特殊意义,我们需要\$表示,所以替换函数就成了 content.replace(/\$/g,”$$$$”).
Done. bug fix了,以后学习的时候还是要细心和细节和深度呢。。
浙公网安备 33010602011771号