jQuery用于textarea的输入过滤器

And*_* SK 3 javascript regex jquery filter keyup

将此解决方案调整为脚本。这样做的目的是防止用户键入未经授权的字符(当然,后端也有一个过滤器)。

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

它很好用,但是我还需要用户输入允许的特定字符,例如:。,!??ñáéíóú-我的意思是,基本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);
});
Run Code Online (Sandbox Code Playgroud)

Mic*_*ski 5

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

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

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