Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

search for backslash

I've JavaScript which searches for eg. a letter in a string and outputs "ok" if the letter is not there and "not ok" if the letter is there:

 var term = "term";
 var slash = "a";
 var search =term.search(slash);

 if(search==-1)
 "ok";
 else
 "not ok";

The problem is that I want this to work with a backslash too. The strange thing is, searching for 2 backslashes in a row works, so "term" outputs "ok" and "term\\" outputs "not ok":

 var term = "term";
 var slash = "\\\\";
 var search =term.search(slash);

 if(search==-1)
 "ok";
 else
 "not ok";

But searching for 1 backslash doesn't work, so this code gives an error:

 var term = "term";
 var slash = "\\";
 var search =term.search(slash);

 if(search==-1)
 "ok";
 else
 "not ok";

Hope someone sees the error. Thanks!

like image 973
Steven Avatar asked Oct 09 '22 22:10

Steven


1 Answers

There are two layers of interpretation involved with making a regular expression in JavaScript. The first is that of the string syntax, and you've correctly doubled your backslashes to account for that. However, the string will itself be interpreted by the regular expression syntax analysis code, and that will have a problem with a single lone backslash. In other words, a regular expression consisting of a single backslash is a syntax error; it's simply not allowed. If you want to search for a single backslash, you need a regular expression with two backslashes in it.

Making a regular expression with the native literal regular expression syntax makes this more obvious:

var r1 = /\\/; /* this is OK */
var r2 = /\/;  /* this is not OK */
like image 134
Pointy Avatar answered Oct 12 '22 10:10

Pointy