regex - why won't this work?

T

Trev

Hi everyone,
I've got a very simple piece of code, and it doesn't work. I'm stumped!

var pattern1="arthur/i";

var stringtosearch = "ARTHUR and GEORGE's guest house";

pattern1.test(stringtosearch);

This should return true, but it returns false! Can anyone see what is
wrong?

TIA

Trev
 
P

p.lepin

Trev said:
var pattern1="arthur/i";

var stringtosearch = "ARTHUR and GEORGE's guest house";

pattern1.test(stringtosearch);

This should return true, but it returns false!

Actually, it should say something along the lines of
'pattern1.test is not a function'.
Can anyone see what is wrong?

Sure, replace

var pattern1="arthur/i";

with

var pattern1 = /arthur/i ;
 
L

Lee

Trev said:
Hi everyone,
I've got a very simple piece of code, and it doesn't work. I'm stumped!

var pattern1="arthur/i";

var stringtosearch = "ARTHUR and GEORGE's guest house";

pattern1.test(stringtosearch);

This should return true, but it returns false! Can anyone see what is
wrong?

Actually, what that should do is tell you that pattern1.test is not
a function, because "arthur/i" is not a RegExp.
It's just a string that happens to end in "/i".

var pattern1=/arthur/i;
or
var pattern1 = new RegExp("arthur","i");


--
 
S

shimmyshack

var stringtosearch = "ARTHUR and GEORGE's guest house";
var reg = /arthur/i;
if ( reg.test( stringtosearch ) == true )
{
alert( 'yippee' );
}
else
{
alert( 'nope' );
}
 
T

Tom Cole

shimmyshack said:
var stringtosearch = "ARTHUR and GEORGE's guest house";
var reg = /arthur/i;
if ( reg.test( stringtosearch ) == true )
{
alert( 'yippee' );
}
else
{
alert( 'nope' );
}

Trev,

Notice that the regex does not have quotes around it. If you quote it,
it is not a regex, it becomes a string. String does not have a test
method AFAIK.

HTH.
 
T

Trev

Thanks - I figured out what had gone wrong (missed out a trailing ";").
Grrrrr!

Now for my next trick:
var myURL = document.referrer;
var mySearch = /george/i;

and then do a check on mySearch.test(myURL)....should work OK.....
 
M

mick white

Trev said:
Thanks - I figured out what had gone wrong (missed out a trailing ";").
Grrrrr!

Now for my next trick:
var myURL = document.referrer;
var mySearch = /george/i;

and then do a check on mySearch.test(myURL)....should work OK.....
var d;
var containsGeorge=
(d=document.referrer) && /george/i.test(d);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top