最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Regex javascript allow only numbers, alphabets and underscore - Stack Overflow

programmeradmin4浏览0评论

I'm using this code to prevent people from puting spaces between alphabets and numbers. I would lilke to modify the code so that only alphabets, letters and numbers can be typed.

This is what i'm doing:

 replace(/\sg, '') oin javascript

Can anyone help me as to how to costrucrt the regex expression so that only alphavets, nnumbers, underscore and no space can be keyed in the input box

Thanks

I'm using this code to prevent people from puting spaces between alphabets and numbers. I would lilke to modify the code so that only alphabets, letters and numbers can be typed.

This is what i'm doing:

 replace(/\sg, '') oin javascript

Can anyone help me as to how to costrucrt the regex expression so that only alphavets, nnumbers, underscore and no space can be keyed in the input box

Thanks

Share Improve this question asked Aug 26, 2013 at 1:31 Kwaasi DjinKwaasi Djin 1252 silver badges11 bronze badges 2
  • Have you tried to learn how to pose regular expressions? – zerkms Commented Aug 26, 2013 at 1:33
  • Please, take a look at the update here. – Ravi K Thapliyal Commented Aug 26, 2013 at 3:53
Add a ment  | 

2 Answers 2

Reset to default 4

Here's how you could do it with jQuery:

$(function() {
    $( '#username' ).on( 'keydown', function( e ) {
        if( !$( this ).data( "value" ) )
             $( this ).data( "value", this.value );
    });
    $( '#username' ).on( 'keyup', function( e ) {
        if (!/^[_0-9a-z]*$/i.test(this.value))
            this.value = $( this ).data( "value" );
        else
            $( this ).data( "value", null );
    });
});

SQL Fiddle Demo

Perhaps you want something like this:

var input = "f%o@o";
var output = input.replace(/\W/g, ''); // "foo"

This will remove any non-word character (a word character is a letter, number, or underscore) from the input string.

发布评论

评论列表(0)

  1. 暂无评论