我的源数据如下所示:
ab
ab
我在其上运行以下内容:
function lintPost(postText) {
var replacements = {
a : "4",
b : "BBBB"
}
for (var pattern in replacements) {
if (replacements.hasOwnProperty(pattern)) {
var postText = postText.replace(pattern, replacements[pattern], "gm");
console.log(postText);
}
}
return postText;
};
我回过头来看:
4BBBB
ab
意思是,尽管同时使用了全局和多行标记,regexen仍然只应用于第一行 - JS似乎在第一个换行符时停止匹配。
输出应该是
4BBBB
4BBBB
我只用了g,只用了m,即使是y - 没什么。
为什么JavaScript不匹配源数据中的其他行?
答案 0 :(得分:2)
String.replace方法中flags参数的使用是非标准的。不要使用此参数,而是使用带有相应标志的RegExp对象。
所以改变你的代码:
var postText.replace(new RegExp(pattern,"gm"), replacements[pattern]);