[英]Javascript - Regex - Replace every other match in string with different strings
So I have my code like this: 所以我有这样的代码:
for (var i = 0; i < str.length; i++) {
str = str.replace("|", "Math.abs(");
str = str.replace("|", ")");
}
Is there anyway to get the same effect using a regex? 反正有使用正则表达式获得相同的效果吗?
Or at least a regex with a function?: 或至少具有功能的正则表达式?:
str = str.replace(/?/g, function() {?});
You can use this single regex replace
method: 您可以使用以下单个正则表达式replace
方法:
str = str.replace(/\|([^|]+)\|/g, 'Math.abs($1)');
You can match the string between |
您可以在|
之间匹配字符串 s and then replace them with whatever string you want s,然后将其替换为所需的任何字符串
str[i] = str[i].replace(/\|(.*?)\|/g, "Math.abs($1)");
For example, 例如,
var str = ["|1|", "|-2|+|22 * -3|"];
for (var i = 0; i < str.length; i++) {
str[i] = str[i].replace(/\|(.*?)\|/g, "Math.abs($1)");
}
console.log(str);
# [ 'Math.abs(1)', 'Math.abs(-2)+Math.abs(22 * -3)' ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.