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语句有什么问题。我怎样才能让它发挥作用?
答案 0 :(得分:0)
检查搜索是否返回-1但不是真。
答案 1 :(得分: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")