javascript - Replace X with Y and Y with X in a single Regular Expression -


say have following:

var strrandomstring = "i have 2 apples , 6 oranges , 3 grapes"; 

now want replace word "apples" word "oranges" , vice-versa. order not fixed , replace should global. makes end result:

document.write(strrandomstring) \\"i have 2 oranges , 6 apples , 3 grapes"; 

currently, best way can think is:

strrandomstring=strrandomstring.replace("apples","*******"); strrandomstring=strrandomstring.replace("oranges","apples"); strrandomstring=strrandomstring.replace("*******","oranges"); 

is there way single replace?

string.prototype.replace not accepts string replacement, accepts function. return value of function used replacement string.

var strrandomstring = "i have 2 apples , 6 oranges , 3 grapes"; strrandomstring.replace(/apples|oranges/g, function(m) {     // `m` matched string.     return m === 'apples' ? 'oranges' : 'apples'; }) // => "i have 2 oranges , 6 apples , 3 grapes" 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -