2015-10-22 21 views
0

我使用的替代方法,如果我輸入「考試考試」只有第一個測試被轉化爲好,因此它會變成「很好的考驗。」我對這種情況發生的原因感到茫然。在一個側面的問題,如果我是加入其他20個字,我想換掉,我會必須創建20個不同的str.replace?簡單的Javascript在html文本框轉換。不工作時兩次

<!DOCTYPE html> 
<html> 
<body> 

<p>Click the button to replace "Test" with "Good"</p> 

<textarea id="firstbox"></textarea> 
<textarea id="secondbox"></textarea> 

<button onclick="myFunction()">Change</button> 

<script> 
    function myFunction() { 
     var str = document.getElementById("firstbox").value.toLowerCase() 
     var res = str.replace("test", "good"); 
     document.getElementById("secondbox").value = res; 
    } 
</script> 

</body> 
</html> 

任何幫助,將不勝感激

回答

2

使用正則表達式,改變"good"/good/g

function myFunction() { 
 
     var str = document.getElementById("firstbox").value.toLowerCase() 
 
     var res = str.replace(/test/g, "good"); 
 
     document.getElementById("secondbox").value = res; 
 
    }
<p>Click the button to replace "Test" with "Good"</p> 
 

 
<textarea id="firstbox"></textarea> 
 
<textarea id="secondbox"></textarea> 
 

 
<button onclick="myFunction()">Change</button>

+0

你好,你知道我怎麼可以把多個替換字符串,整理像字典翻譯。 – Archie

+0

你能舉個例子嗎?你的意思是你想用一個詞來替換多個單詞,或者你有地圖的話,你要替換翻譯(例VAR地圖= {「試驗」:「好」,「測試2」:壞了,等}) ? – depperm