3

将此解决方案改编为我的脚本。这个想法是为了防止用户输入未经授权的字符(当然后端还有一个过滤器)。

$('#someinput').keyup(function() {
    var $th = $(this);
    $th.val( $th.val().replace(/[^a-zA-Z0-9]/g, function(str) {
        console.log(str);
        return '';
    }))
})

它很好用,但我还需要用户能够输入特定的允许字符,例如:.,!?ñáéíóú - 我的意思是,基本的 a-zA-Z0-9 加上一些基本字符和一大堆特殊语言字符.

实际上需要省略的是:@#$%^&*()=_+"':;/<>\|{}[]

有任何想法吗?谢谢!

感谢迈克尔的解决方案

//query
$('#someinput').keyup(function() {
    var $th = $(this);
    $th.val($th.val().replace(/[@#$%\^&*()=_+"':;\/<>\\\|{}\[\]]/g,function(str){return '';}));
}).bind('paste',function(e) {
    setTimeout(function() {
        $('#someinput').val($('#someinput').val().replace(/[@#$%\^&*()=_+"':;\/<>\\\|{}\[\]]/g,function(str){return '';}));
        $('#someinput').val($('#someinput').val().replace(/\s+/g,' '));
    },100);
});
4

2 回答 2

5

反转您的正则表达式以仅替换您想要省略的特定字符:

$th.val( $th.val().replace(/\s?[@#$%\^&*()=_+"':;\/<>\\\|{}\[\]]/g, ""));
// Edit: added optional \s to replace spaces after special chars

请注意,其中一些需要在[]字符类中使用反斜杠进行转义:\\\[\]\^\/

于 2011-12-08T14:54:18.910 回答
3

如果我理解您想要做什么,您不能将那些不需要的字符添加到您的正则表达式中而不是执行[^a-zA-Z0-9]?

将其替换为[@#\$%\^&\*\(\)=_\+"':;\/<>\\\|\{\}\[\]](注意转义)

于 2011-12-08T14:54:37.640 回答