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(pa开发者_如何学JAVAtt1));
Thanks, Gaurav
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.
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
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));
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*)?$';
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/
精彩评论