2016-06-06 14 views
0

Ich möchte wie mit Bs und umgekehrt austauschen, die mehrmals in einer Zeichenfolge angezeigt werden.Tauschen Wörter in JavaScript

function temp(a,b) { 
    console.log('The first is ' + b + ' and the second is ' + a + ' and by the way the first one is ' + b); 
} 
temp('a','b') 
eval(temp.toString().replace('first','second')); 
eval(temp.toString().replace('second','first')); 
temp('a','b'); 

Dies funktioniert nicht, aber ich mag folgendes Ergebnis erhalten:

The first is a and the second is b and by the way the first one is a 
+0

warum nicht 'Temp ('b', 'a')?' –

Antwort

0

String.prototype.replace wird nur das erste Auftreten eines Spiels ersetzen, wenn Sie eine Zeichenfolge geben.

function temp(a,b) { 
 
    console.log('The first is ' + b + ' and the second is ' + a + ' and by the way the first one is ' + b); 
 
} 
 
temp('a','b') 
 
eval(temp.toString().replace('first','second')); 
 
temp('a','b');

so, was Sie oben im Code tun wird, um die erste Instanz von first mit second dann Zurückschalten Schalten aus.

Sie könnten stattdessen einen regulären Ausdruck übergeben, bei dem das globale Flag gesetzt ist, um alle Instanzen eines Wortes zu ersetzen. Außerdem können Sie eine Funktion an replace übergeben, um zu handhaben, mit was jedes Match ersetzt werden sollte.

function temp(a,b) { 
 
    console.log('The first is ' + b + ' and the second is ' + a + ' and by the way the first one is ' + b); 
 
} 
 
temp('a','b') 
 

 
// Match 'first' or 'second' 
 
var newTemp = temp.toString().replace(/(first|second)/g, function(match) { 
 
    // If "first" is found, return "second". Otherwise, return "first" 
 
    return (match === 'first') ? 'second' : 'first'; 
 
}); 
 
eval(newTemp); 
 
temp('a','b');

Verwandte Themen