0

假设我有以下 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;
    }
}

因此,我怎样才能只删除不可接受的字符?

4

2 回答 2

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;
    }
}
于 2013-04-23T05:07:21.507 回答
0

要替换非拉丁字符,您可以使用:

function removeNonLatin(arg) {
    var nonlatin = /!(^[\u0020-\u007E]*$)/g;
    arg = arg.replace(nonlatin , '');
    return arg;
}
于 2013-04-23T05:17:24.833 回答