我想用<>
替换匹配的()
和[]
对。例如,
abc(def)hij -> abc[def]hij
abc<def>hij -> abc[def]hij
我所做的是这样的:
function getParensReplaced(str) {
return str && str.replace(/<([^>]+)>/g, function(str, p){
return '[' + p + ']';
}).replace(/\(([^\)]+)\)/g, function(str, p){
return '[' + p + ']';
});
}
但这看起来并不好。有任何改进的想法吗?
最佳答案
怎么样:
\([^\)]*?\)|<[^>]*?>
这样就可以:
function getParensReplaced(str) {
return str && str.replace(/\(([^\)]*?)\)|<([^>]*?)>/g, function(str, p,q){
return (p == undefined) ? '[' + q + ']': '[' + p + ']';
});
}
JSfiddle:http://jsfiddle.net/GgrQm/
关于javascript - 优雅的替换括号的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8599962/