|
-
May 21st, 2002, 03:57 AM
#1
Thread Starter
Hyperactive Member
What is error in this JavaScript code
Code:
var X="http://www.vbzoom.com";
if(X.match("http://")!="http://")
{
alert("Error Site.");
}
-
May 21st, 2002, 04:45 AM
#2
Hyperactive Member
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 :
Code:
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 :
Code:
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.
-
May 21st, 2002, 05:40 AM
#3
Frenzied Member
You'd probably be better off using indexOf in this case wouldn't you?
-
May 21st, 2002, 05:45 AM
#4
Hyperactive Member
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 !
-
May 21st, 2002, 05:58 AM
#5
-
May 21st, 2002, 11:27 AM
#6
Frenzied Member
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 $.
Travis, Kung Foo Journeyman
As always, RTFM.
WWW Standards: HTML 4.01, CSS Level 2, ECMA 262 Bindings to DOM Level 1, JavaScript 1.3 Guide and Reference
Perl: Learn Perl, Llama, Camel, Cookbook, Perl Monks, Perl Mongers, O'Reilly's Perl.com, ActiveState, CPAN, TPJ, and use Perl;
YBMS, but Mozilla doesn't.
-
May 21st, 2002, 11:33 AM
#7
Hyperactive Member
note: If the 'http://' is at the start of the string indexOf will return 0 which is equivalent to false.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|