Gaurav Pandey
Gaurav Pandey

Reputation: 2796

problem using regular expressions with javascript

I am using the following script but it's giving syntax errors which I am unable to figure out. Please help.

var str = "http://gaurav.com";

var patt1 = /^http\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$/;
console.log(str.match(patt1));

Thanks, Gaurav

Upvotes: 0

Views: 74

Answers (5)

Rakesh Sankar
Rakesh Sankar

Reputation: 9415

You pattern gives a "," in the string, could that be the problem???

Try this:

var str = "http://gaurav.com";
var patt1 = 'http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}';
console.log(str.match(patt1));

See the working example here

Upvotes: 1

NullRef
NullRef

Reputation: 3743

Needs to be in /'s

var patt1 = /^http\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?$/;

Edit: also escape /s in the pattern.

Upvotes: 2

Salman Arshad
Salman Arshad

Reputation: 272026

You must escape all / as well:

var str = "http://gaurav.com";
var patt1 = /^http\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?$/;
//------------------^-^---------------------------------^
console.log(str.match(patt1));

Upvotes: 0

user1921
user1921

Reputation:

This seems to work just fine - looks like you're just missing your quotes

var str = "http://gaurav.com";

var patt1 = "^http\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$";
document.write(str.match(patt1));

Here's a jsfiddle link to the code you can play with http://jsfiddle.net/chuckplayer/fLrx8/

Upvotes: 0

Bing
Bing

Reputation: 746

Quote the regexp string, that should fix the error. Haven't checked the expression, but that wasn't the question, right?

var patt1 = '^http\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$';

Upvotes: 0

Related Questions