2012-06-14 4 views
5

Solo chiedendo il modo migliore per sostituire le corrispondenze in posto su una stringa.Scorrere le corrispondenze di espressioni regolari di Javascript per modificare la stringa originale

value.replace("bob", "fred"); 

per esempio, funziona, ma voglio ogni istanza di "bob" per essere sostituito con una stringa casuale ho memorizzato in una matrice. Fare una corrispondenza regolare mi restituisce il testo corrispondente, ma non mi consente di sostituirlo nella stringa originale. C'è un modo semplice per fare questo?

Per esempio mi aspetterei la stringa:

"Bob went to the market. Bob went to the fair. Bob went home" 

Per forse saltar fuori come

"Fred went to the market. John went to the fair. Alex went home" 

risposta

4

È possibile sostituire con il valore di una chiamata di funzione:

var names = ["Fred", "John", "Alex"]; 
var s = "Bob went to the market. Bob went to the fair. Bob went home"; 
s = s.replace(/Bob/g, function(m) { 
    return names[Math.floor(Math.random() * names.length)]; 
}); 

Questo per esempio:

"John went to the market. Fred went to the fair. John went home" 
+0

Whoa. È perfetto. Grazie! – Grazfather

Problemi correlati