i want swap bs , vice versa appear multiple times in string.
function temp(a,b) { console.log('the first ' + b + ' , second ' + + ' , way first 1 ' + b); } temp('a','b') eval(temp.tostring().replace('first','second')); eval(temp.tostring().replace('second','first')); temp('a','b');
this not work following outcome:
the first , second b , way first 1
string.prototype.replace
replace first occurrence of match if give string.
function temp(a,b) { console.log('the first ' + b + ' , second ' + + ' , way first 1 ' + b); } temp('a','b') eval(temp.tostring().replace('first','second')); temp('a','b');
so you're doing in code above switching out first instance of first
second
switching back.
instead, pass regular expression global flag set replace instances of word. furthermore, can pass function replace
handle each match should replaced with.
function temp(a,b) { console.log('the first ' + b + ' , second ' + + ' , way first 1 ' + b); } temp('a','b') // match 'first' or 'second' var newtemp = temp.tostring().replace(/(first|second)/g, function(match) { // if "first" found, return "second". otherwise, return "first" return (match === 'first') ? 'second' : 'first'; }); eval(newtemp); temp('a','b');