Bogdan
Bogdan

Reputation: 1911

why does string.search fail in this instance?

I'm pasting the exact strings that javascript prints:

string: "testare atasament fisier,tip nota - reamintire (1),Diverse,Telefon,Fisier,tip nota Azom" without the ""

substring: "tip nota - reamintire (1)" again without the ""

just writing those "" to show that there are no empty spaces anywhere funny (also checked in the code)

The result of

string.search(substring);

is always -1, how come? which character is messing up the search?

note that i don't use the names string and substring for the variables in my actual code

Upvotes: 2

Views: 106

Answers (3)

Jean-Charles
Jean-Charles

Reputation: 1720

This is because search function has a regexp as parameter. You have to escape the parentheses with \\:

var string= "testare atasament fisier,tip nota - reamintire (1),Diverse,Telefon,Fisier,tip nota Azom" ;
var substring = "tip nota - reamintire (1)" ;
var substring2 = "tip nota - reamintire \\(1\\)" ;

alert(string.search(substring)); // -1 
alert(string.search(substring2)); // 25

Upvotes: 2

Guffa
Guffa

Reputation: 700840

The search method takes a regular expression object, and if you give it a string, it's used to create a regular expression object.

Reference: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/search

The ( and ) have a special meaning in a regular expression, so they are not included in the characters that should be matched. You will actually be looking for the string "tip nota - reamintire 1".

You can use the \ character to escape the characters in the regular expression. If you use them in a string literal, you have to escape the \ characters, so:

var substring = "tip nota - reamintire \\(1\\)";

You can also use a regular expression literal:

var substring = /tip nota - reamintire \(1\)/;

Upvotes: 3

John Strickler
John Strickler

Reputation: 25421

It worked for me - using indexOf

"testare atasament fisier,tip nota - reamintire (1),Diverse,Telefon,Fisier,tip nota Azom"
.indexOf("tip nota - reamintire (1)");

yields

25

search takes a regular expression where indexOf takes a string.

The parenthesis inside of "tip nota - reamintire (1)" act as a group, you would have to escape them for it to match an actual parenthesis.

Upvotes: 2

Related Questions