Click to See Complete Forum and Search --> : What is error in this JavaScript code
prokhaled
May 21st, 2002, 03:57 AM
Code:
var X="http://www.vbzoom.com";
if(X.match("http://")!="http://")
{
alert("Error Site.");
}
progressive
May 21st, 2002, 04:45 AM
I'm guessing that you want the alert box to be shown if the
string X doesn't contain http://
is so then you need to do the following.
first - the match() method returns true or false so you don't need the
!="http://"
second - when using match you need to use a regular expression
these are defined using / / to contain the regular expression
(regex).
so the correct use of match is :
string.match(/regex/)
third - regex's can't contain special charachters such as /'s unless they are escaped with a \ so to use /'s they need to be coded as \/.
so your correct code is :
var X="http:/www.vbzoom.com";
if(!X.match(/http:\/\//))
{
alert("Error Site.");
}
note: we are using ! in front of the statement to reverse the outcome of the match method.
So if the statment matches http:// then it returns true we then reverse it with ! so that it retuns false resulting in the alert not being displayed.
Alternativley: if the match statement doesn't find http:// then it returns false we then use ! to turn the false into true resulting in the alert box being shown.
Rick Bull
May 21st, 2002, 05:40 AM
You'd probably be better off using indexOf in this case wouldn't you?
progressive
May 21st, 2002, 05:45 AM
You mean rather than using ! on the outcome, as index of returns -1 if it's not found ?
Personal preference really isn't it I suppose !
Rick Bull
May 21st, 2002, 05:58 AM
Yep :D Although is RegExp slower than indexOf? I have no idea, but I suppose the difference would be so small it'd make no difference. :rolleyes:
CiberTHuG
May 21st, 2002, 11:27 AM
The advantage of indexOf is not speed, but whether or not "http://" comes at the begining of the line, or elsewhere. Since you are trying to test a URL for a certain protocol....
'Course, you can do that in the RegEx with $.
progressive
May 21st, 2002, 11:33 AM
note: If the 'http://' is at the start of the string indexOf will return 0 which is equivalent to false.
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.