假设我有以下JS代码,我只能在收到不可接受的字符时删除整个字符:
function checkInput() {
document.getElementById("message").setAttribute('maxlength', (456));
for (var i = 0; i < document.fr_upload.message.value.length; i++) {
if (!checkLatin(document.fr_upload.message.value)) {
alert("Your entry does not contain latin type.\n Please try again.")
document.fr_upload.message.value = '';
document.fr_upload.char_left.value = 0;
return false;
}
}
}
function checkLatin(arg) {
var latin = /^[\u0020-\u007E]*$/;
if (arg.match(latin)) {
return true;
} else {
return false;
}
}
因此,我怎样才能删除不可接受的字符?
答案 0 :(得分:1)
尝试
function checkInput() {
document.getElementById("message").setAttribute('maxlength', (456));
var value = document.fr_upload.message.value;
if (value && !/[^\u0020-\u007E]/.test(value)) {
alert("Your entry contains non latin characters.\n Please try again.");
document.fr_upload.message.value = value.replace(
/[^\u0020-\u007E]/g, '');
document.fr_upload.char_left.value = document.fr_upload.message.value.length;
}
}
答案 1 :(得分:0)
要替换您可以使用的非拉丁字符:
function removeNonLatin(arg) {
var nonlatin = /!(^[\u0020-\u007E]*$)/g;
arg = arg.replace(nonlatin , '');
return arg;
}