Reputation: 1434
I want to swap As with Bs and vice versa which appear multiple times in a string.
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');
This does not work but I would like to get the following outcome:
The first is a and the second is b and by the way the first one is a
Upvotes: 0
Views: 844
Reputation: 32511
String.prototype.replace
will only replace the first occurrence of a match if you give it a string.
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');
so what you're doing in your code above is switching out the first instance of first
with second
then switching it back.
Instead, you could pass it a regular expression with the global flag set to replace all instances of a word. Furthermore, you can pass a function to replace
to handle what each match should be replaced with.
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');
Upvotes: 1