views:

41

answers:

2

Hi all,

I am trying to validate a twitter url, so that at least it contains a username. I do 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

A: 

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')
Gumbo
Thank you all for the clarificationMuch appreciated
Thomas
A: 

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+)/;
nickf