正在开发 Outlook 加载项,该加载项使用正则表达式将“{First Name|Default=Friend}”和“{Last Name}”字符串替换为联系人的实际名字和姓氏。通过 Google Chrome 在 Outlook Online 中测试时,正则表达式工作正常,但在 Outlook for Mac 中则不然,后者显然使用 Netscape 版本 5(或者至少是 navigator.userAgent 下出现的浏览器)。
String.prototype.replaceAll = function (str1, str2, ignore) {
return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g, "\\$&"), (ignore ? "gi" : "g")), (typeof (str2) == "string") ? str2.replace(/\$/g, "$$$$") : str2);
}
function replaceNames(){
var content = "{First Name|Default=Friend} {Last Name}"
var firstName = "Ted";
var lastName = "Doe";
let currentContent = content.replaceAll('{First Name|Default=Friend}', firstName);
currentContent = currentContent.replaceAll('{Last Name}', lastName);
console.log(currentContent);
}
replaceNames();
Chrome 73 返回内容为:Ted Doe
Netscape 5(来自 Outlook for Mac)返回内容为:Ted {Last Name}
可能出了什么问题?
最佳答案
怎么了
function replaceNames() {
var content = "{First Name|Default=Friend} {Last Name}"
var firstName = "Ted";
var lastName = "Doe";
let currentContent = content.replace(/{First Name\|Default=Friend}/g, firstName);
currentContent = currentContent.replace(/{Last Name}/g, lastName);
console.log(currentContent);
}
replaceNames();
关于javascript - 为什么我的正则表达式仅在某些浏览器中有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56726214/