0

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
1
  • why not temp('b', 'a')? Commented Jun 6, 2016 at 22:07

1 Answer 1

1

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');

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.