複数の文字列を同一の文字列に置換する
例
「apple,banana」を「cucumber」に置換する。
var str="apple2 banana3 orange8 cucumber0"
str=str.replace(/(apple)|(banana)/g,"cucumber")
console.log(str) // cucumber2 cucumber3 orange8 cucumber0
複数の文字列をそれぞれ別の文字列に置換する
例1
「one,two,three」を「three,two,one」に置換する。
function replacer(match,m1,m2,m3,offset,string){
console.log([match,m1,m2,m3,offset,string].join(","))
// one two three,one,two,three,0,one two three go
return [m3,m2,m1].join(" ")
}
var str="one two three go"
str=str.replace(/(one).*(two).*(three)/,replacer)
console.log(str) // three two one go
str=str.replace(/(one).*(two).*(three)/,"$3 $2 $1")
console.log(str) // three two one go
例2
「The apple is round and juicy」を「The cucumber is long and green」に置換する。
function replacer(match,m1,m2,offset,string){
console.log([match,m1,m2,offset,string].join(","))
// apple is round and juicy, is , and ,4,The apple is round and juicy
return "cucumber"+m1+"long"+m2+"green"
}
var str="The apple is round and juicy";
str=str.replace(/apple(.*)round(.*)juicy/,replacer);
console.log(str) // The cucumber is long and green
例3
「apple,banana」が0でなければ「cucumber」に置換し、「cucumber」が0の場合「apple」に置換する。
function replacer(match, m1, m2, m3, m4, m5, m6, offset, string) {
var number = m2 || m4 || m6, food = m1 || m3 || m5;
var str = food == "cucumber" && number == "0" ? "apple" + number : number != 0 ? "cucumber" + number : food + number;
return str
}
var reg = /(apple)([\d]*)|(banana)([\d]*)|(cucumber)([\d]*)/g;
var str = "--- apple0 banana27 orange8 cucumber5"
console.log(str.replace(reg, replacer)) // --- apple0 cucumber27 orange8 cucumber5
var str2 = "--- apple10 banana6 orange8 cucumber0"
console.log(str2.replace(reg, replacer)) // --- cucumber10 cucumber6 orange8 apple0