开发者

Validate twitter URL

I am trying to validate a twitter url, so that at least it contains a username. I do开发者_StackOverflow中文版 not care if it exists or not, just that there is one.

I am using the below javascript regex

var re = new RegExp('((http://)|(www\.))twitter\.com/(\w+)');
alert(re.test('http://twitter.com/test_user'));

but it is not working.

The strange thing is that I created and tested the above regex at this URL

http://www.regular-expressions.info/javascriptexample.html

where it works just fine.

Any ideas?

Thanks


function isTwitterHandle(handle) { 
  if (handle.match(/^((?:http:\/\/)?|(?:https:\/\/)?)?(?:www\.)?twitter\.com\/(\w+)$/i) || handle.match(/^@?(\w+)$/)) return true;
  return false;
}


You need to escape the backslashes in the escape sequences too:

var re = new RegExp('((http://)|(www\\.))twitter\\.com/(\\w+)');

And I would recommend this regular expression:

new RegExp('^(?:http://)?(?:www\\.)?twitter\\.com/(\\w+)$', 'i')


It's because of the way you're defining the regex by using a string literal. You need to escape the escape characters (double backslash):

'^(http://)?(www\.)?twitter\.com/(\\w+)'

In the above, I also changed the start so that it would match http://www.twitter.com/test_user.

Alternatively, use the RegExp literal syntax, though this means you have to escape /:

var re = /^http:\/\/)?(www\.)?twitter\.com\/(\w+)/;


-http://twitter.com/username (this is http) -https://twitter.com/username (this is https) -twitter.com/username (without http) -@username( with @) -username (without @)

var username  = "@test";
    var r1 = new RegExp('^((?:http://)?|(?:https://)?)?(?:www\\.)?twitter\\.com/(\\w+)$', 'i');
            if (r1.test(username) == false) {
                var r2 = new RegExp('^@?(\\w+)$', 'j');
                if (r2.test(username) == true)
                    return true;
                else
                    return false;
            } else {
                return true;
            }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜