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
Post a Comment