我从 .getAttribute() 获得了以下字符串:
ctl00$m$g_ff7ec6ac_ec2e_4402_aaaa_7fcce245ff1b$ctl03$_UserName
我们称之为“字符串”。现在我需要将 $ 替换为 _ 。我尝试过:
String.replace(/\$/g, "\_");
...不起作用。
第二次尝试:
String.replace(/$$/g, "\_");
...不起作用。
第三次尝试:
String.replace(/\$$/g, "\_");
...不起作用。
那么...有人可以帮忙吗?感谢大家的努力!
编辑:需要使其适用于 IE8/9
此时的代码:
mailName = document.body.innerHTML.match(/ctl00\$.+EmailAddress/);
alert(mailName); // String is "ctl00$m$g_ff7ec6ac_ec2e_4402_aaaa_7fcce245ff1b$ctl03$_UserName"
mailName2 = mailName.replace(/\$/g, "_");
编辑2:
...我自己找到了答案。
mailName = document.body.innerHTML.match(/ctl00\$.+EmailAddress/);
返回一个字符串,但 .replace() 或 .split() 无法使用它。要开始工作,你需要这样做
mailID = '"' + document.body.innerHTML.match(/ctl00\$.+EmailAddress/) + '"';
之后一切都很好。不知道为什么,但在 IE8/9 中这个解决方案效果很好。
最佳答案
使用
yourString = yourString.replace(/\$/g, "_");
无需转义第二个字符串。
来自the MDN :
Returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.
另请注意,替换不会更改原始字符串。您需要取回返回值。
并且,关于您的编辑,请注意 match function of Internet Explorer即使没有 g
修饰符,似乎也会返回一个数组:
If the match method does not find a match, it returns null. If it finds a match, match returns an array, and the properties of the global RegExp object are updated to reflect the results of the match.
你可以做到
var str = ''+ document.body.innerHTML.match(/ctl00\$.+EmailAddress/);
关于javascript - 需要用Javascript替换 "$"为 "_",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13235252/