我想在B中交换As,反之亦然,在字符串中多次出现。
function temp(a,b) {
console.log('The first is ' + b + ' and the second is ' + a + ' and by the way the first one is ' + b);
}
temp('a','b')
eval(temp.toString().replace('first','second'));
eval(temp.toString().replace('second','first'));
temp('a','b');
这不起作用,但我希望得到以下结果:
The first is a and the second is b and by the way the first one is a
答案 0 :(得分:0)
String.prototype.replace
只会替换第一次出现的匹配。
function temp(a,b) {
console.log('The first is ' + b + ' and the second is ' + a + ' and by the way the first one is ' + b);
}
temp('a','b')
eval(temp.toString().replace('first','second'));
temp('a','b');
所以你在上面的代码中所做的就是用first
切换second
的第一个实例,然后将其切换回来。
相反,您可以将正则表达式传递给它,并设置全局标志以替换单词的所有实例。此外,您可以将函数传递给replace
以处理每个匹配应替换的内容。
function temp(a,b) {
console.log('The first is ' + b + ' and the second is ' + a + ' and by the way the first one is ' + b);
}
temp('a','b')
// Match 'first' or 'second'
var newTemp = temp.toString().replace(/(first|second)/g, function(match) {
// If "first" is found, return "second". Otherwise, return "first"
return (match === 'first') ? 'second' : 'first';
});
eval(newTemp);
temp('a','b');