searching a string surrounded by pipes using regular expressions

S

silly putty

hello. this is all the code in my javascript. there's nothing else in
the html page except for the following:

var regex = new RegExp("\|A\|");
if (regex.test("8_2006|13|15|31|"))
alert("success");
else
alert("fail");

if i run the above code, i get the "success" message box, but shouldn't
the "fail" message appear instead? the regular expression is defined
as the character A surrounded by a pipe on each end, but there's no
instance of that expression in my string when i perform the test. can
someone please help? thanks
 
R

RobG

silly said:
hello. this is all the code in my javascript. there's nothing else in
the html page except for the following:

var regex = new RegExp("\|A\|");

When constructing regular expressions that way, you need to
double-quote special characters that you want to quote:

var regex = new RegExp("\\|A\\|");

Typically the middle part will provided by a variable:

var txt = 'A';
var regex = new RegExp('\\|' + txt + '\\|");

if (regex.test("8_2006|13|15|31|"))

You can also do this test using:

if ( /\|A\|/.test("8_2006|13|15|31|")) {
/* expression is true */
} else {
/* expression is false */
}
 
S

silly putty

that works perfectly. thanks alot!
When constructing regular expressions that way, you need to
double-quote special characters that you want to quote:

var regex = new RegExp("\\|A\\|");

Typically the middle part will provided by a variable:

var txt = 'A';
var regex = new RegExp('\\|' + txt + '\\|");



You can also do this test using:

if ( /\|A\|/.test("8_2006|13|15|31|")) {
/* expression is true */
} else {
/* expression is false */
}
 

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,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top