这是我想要做的一个非常简单的例子。 假设我有这段代码:
function myReplaceFunction(match, p1, p2) {
// If "(fooball:)" got a match
if (p1) {
// Just some condition. This one is stupid, but you get the idea.
if (match === "football:") {
// Don't do anything. Can I not replace from function?
return match;
}
} else if (p2) { // If "(ball:)" got a match
if (match === "ball:") {
return "step:";
}
}
};
var regexp = /(football:)|(ball:)/g;
var originalString = 'something football: something';
var newString = originalString.replace(regexp, myReplaceFunction);
console.log(newString);
结果:“足球:某事”
我想:“一些脚步:某事”
之后(足球:)得到一个匹配,我的功能应该决定不用任何东西替换“足球:”但是我确实想要第二个带括号的子匹配字符串“ball:”将“ball:”替换为“step:”所以结果将是“某种脚步:某种东西”。
我需要给一个(ball :)机会来处理原始字符串... 我能做到吗?如果问题不清楚,请问,我会解释。 谢谢!
答案 0 :(得分:1)
已更新:根据评论中的链接进行了更改。
试一试。我确实构建了从displayName
到systemName
的快速查找以使用:
var fieldNames = [
{ displayName: "Sender", systemName: "from_field"},
{ displayName: "Receiver(addressee)", systemName: "to_field"},
{ displayName: "Author", systemName: "author_id_field"}
],
regex = /(?:#?"?)([^":]+)(?:"?):/i,
map = {
"Sender": "from_field",
"Receiver(addressee)": "to_field",
"Author": "author_id_field"
};
var test = [
'#"Sender":',
'"Sender":',
'Sender:',
'#"Receiver(addressee)":',
'"Receiver(addressee)":',
'Receiver(addressee):',
'#"Unknown":'
];
for (var i=0; i<test.length; i++) {
var systemName = test[i].replace(regex, function(match, p1) {
if (p1) return map[p1] || p1;
});
console.log("Display[%s] = System[%s]", test[i], systemName);
}
// output:
// Display[#"Sender":] = System[from_field]
// Display["Sender":] = System[from_field]
// Display[Sender:] = System[from_field]
// Display[#"Receiver(addressee)":] = System[to_field]
// Display["Receiver(addressee)":] = System[to_field]
// Display[Receiver(addressee):] = System[to_field]
// Display[#"Unknown":] = System[Unknown]
如果匹配的displayname
未知(_i.e。在查找地图中),则只是按原样返回。