Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

regular expressions 2

Status
Not open for further replies.

irate

Programmer
Jan 29, 2001
92
GB
i did post this in the javascript forum first but i have been told regular expressions come from unix so maybe someone who knows unix can help

Im using a regular expression to validate a URL.

function ValidateURL(address)
{
//the regular expression used to validate the URL
var regexpURL = new RegExp("^w{3}\.\w+\.\/\w*\.*\w+", "i");
if (regexpURL.test(address))
return "";
else
return "\n* Invalid URL\n -Valid URLs are in the form ' }

when i use just

var regexpURL = new RegExp("^w{3}\."i");

it works for the first ' but when i add in the rest it doesnt work.
I want to make sure there is www. at the start and then any number of alphanumeric characters then a period then either com or co.uk or ac.uk and the a forward slash and then an optional set of alphanumeric characters and a period and either html or htm or asp ect.

My knowledge of regular expressions isnt that great so any help will be greatly appreciated.
 
irate,
I'm afraid you have been misinformed. The regular expressions used in Javascript are quite different to those supported by most UNIX shells. They are more like the regular expressions supported by Perl. Anyways, with regards to your question. The reason your regular expression is not working as expected is that you are actually initialising the RegExp object using a string. And the string has its own escaping mechanism. An example:

"\w" --> The \w is escaped in the string, but \w does not mean anything special to the string, so 'w' gets passed to the RegExp constructor.

"\\w" --> The \\ is escaped in the string, and \\ corresponds to a literal \, so '\w' gets passed to the RegExp constructor.

A less confusing way of creating a RegExp in Javascript is to use the RegExp literal:

var myRegExp = /\w/;

Which is equivalent to:

var myRexExp = new RegExp( "\\w" );

Hope this hasn't confused you more ;-)

Cheers, Neil
 
Thankyou very much that was staring me in the face the whole time, i should have seen it... anyways it works now this is what im using. Thnaks for the help.

function ValidateURL(address)
{
//the regular expression used to validate the URL
var regexpURL = /^w{3}\.\w+\.\w*\.*\w+\/\w*/i;
if (regexpURL.test(address))
return "passed";
else
return "didnt pass";
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top