2013-05-06 84 views
-4
function clean(e){ 
    var textfield = document.getElementById(e); 
    var regex = /[^a-z 1-9 ,.!?-`'"()\r\n ]/gi; 
    var wrongWords = new Array("can't", "I", "won't"); 
    var rightWords = new Array("can not", "people", "will not"); 
    var x = 0 
    if(textfield.value.search(regex) > -1) { 
     document.getElementById('status').innerHTML = "We found invalid characters"; 
     textfield.value = textfield.value.replace(regex, ""); 
    } 
    while(textfield.value.search(wrongWords) === true){ 
     textfield.value = textfield.value.replace(wrongWords[x], rightWords[x]); 
     x++; 
    } 
} 

while語句有什麼問題。我怎樣才能使它工作?在JavaScript中查找和替換textarea中的單詞

+0

有什麼實際問題? – likeitlikeit 2013-05-06 21:34:24

+0

歡迎來到Stack Overflow。這些問題的答案取決於代碼*應該*做什麼(你沒有描述)。下一次,請包括代碼執行的內容以及它與預期的不同之處(實際結果與預期結果)的簡要說明。幫助別人來幫助你;-) – Leigh 2013-05-07 01:12:17

回答

0

var wrongWords = new Array("can't", "I", "won't"); 
... 
... textfield.value.search(wrongWords) ... 

你調用search這需要一個正則表達式,但因此它最終尋找,因爲正則表達式像/can't,I,won't/越來越單詞的數組強制將數組強制爲RegExp將調用數組toString,該方法將在","上加入。

您可以驗證

RegExp(["foo", "bar"]).source === "foo,bar" 

也許

textfield.value.search(wrongWords[x]) 

會接近你想要什麼,但它不匹配全字。它會發現「我在‘在一年MMXIII,...’

爲了解決這個問題,你可以嘗試邊界檢查:

textfield.value.search("\\b" + wrongWords[x] + "\\b") 
+0

謝謝哦,這麼多。 – user2356132 2013-05-06 23:04:10

0

檢查搜索是否返回-1但不是true。

http://www.w3schools.com/jsref/jsref_search.asp

+0

這應該是一個評論...而w3fools的參考可能會帶給你一個downvote ... :) – PSL 2013-05-06 21:15:12

+1

@PSL gah你有一個無限的遞歸調用你的個人資料頁....悲傷的一天。 :-) – Ryan 2013-05-06 21:34:53

+0

:)是啊... Regd w3schools鏈接我記得得到了 - 投票兩次只是因爲發佈它幾個月回來.. :( – PSL 2013-05-06 21:46:10