2016-05-04 54 views
0

我目前正在開發一個簡單的web應用程序,使用html與JavaScript,我試圖做一個簡單的string.replace調用從一個html textarea收到的字符串像這樣;使用javascript替換HTML字符從html textarea

var contents = document.getElementById("contents").value; 
var alteredText = contents.replace(/£/g, "poundsign"); 

問題是,當字符串中包含£符號時,替換調用找不到它。我看通過控制檯的代碼,似乎隨時有在JavaScript中的$符號它增加了一個「A」到£符號,所以

string.replace(/£/g, "poundsign"); 

,因爲它是寫在js文件將成爲運行時,以下幾點:

string.replace(/£/g, "poundsign"); 

而VAR內容£仍然只是£(把一個£到textarea的引起更換電話正常工作)。有沒有辦法阻止添加到js文件中,或者在調用.replace之前將它添加到html文件中?

Â是隨時添加£出現在js文件中,據我所知,並且我沒有能夠得到它匹配的HTML沒有用戶添加到HTML本身。

+0

string.replace(/£/ g,「poundsign」);你的目標是變量var_string.replace嗎?另外你爲什麼要做「/£/ g」爲什麼不只是「£」?有沒有必要正則表達式呢? – Riddell

+1

你能檢查這個鏈接嗎? http://stackoverflow.com/questions/280712/javascript-unicode-regexes –

+0

可能dup? http://stackoverflow.com/questions/4382518/why-cant-i-display-a-pound-%C2%A3-symbol-in-html – ste2425

回答

0
// replace pound string by empty string 
    var mystr = '£'; 
    mystr = mystr.replace(/£/g,'poundsign'); 
    alert(mystr); 
0

感謝@David Guan的鏈接,這讓我走上了正確的軌道,並對其他所有評論。

當我在.replace調用中使用Unicode編號而不是字符時,問題得到了解決,它能夠在沒有插入的情況下正確匹配英鎊符號。