2016-06-06 2 views
0

문자열로 여러 번 나타나는 Bs와 마찬가지로 바꾸고 싶습니다.자바 스크립트에서 단어 바꾸기

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'); 

이 작동하지 않습니다하지만 다음과 같은 결과를 얻을 싶습니다 : 당신이 그것을 문자열을 주면

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

왜 안'온도 ('B', 'A')? ' –

답변

0

String.prototype.replace는 경기의 첫 번째 항목을 대체합니다. 위의 코드에서하고있는 그래서

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');

는 다시 전환 secondfirst의 첫 번째 인스턴스를 전환한다.

대신 전역 플래그가 설정된 일반 표현식을 전달하여 단어의 모든 인스턴스를 바꿀 수 있습니다. 또한 replace에 함수를 전달하여 각 일치 항목을 대체해야 하는지를 처리 ​​할 수 ​​있습니다.

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');

관련 문제