Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: String.search() can't search "[]" or "()"

Tags:

javascript

If you try searching strings such as "[]" or "()" using the search() function it doesn't work.

function myFunction() {
    var str = "Visit []W3Schools!"; 
    var n = str.search("[]");
    document.getElementById("demo").innerHTML = n;
}

You can try on W3Schools at - https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_search

Searching [] returns -1, while searching () returns 0. Always.

Why is that?

like image 961
kaushal Avatar asked Apr 28 '17 17:04

kaushal


1 Answers

String.search uses a RegExp, and converts its argument to one if it isn't already. [] and () are special characters to RegExp.

You can directly create a regexp and escape the characters like so:

var n = str.search(/\[\]/);

But if you're searching for a literal string, then you should be using String.indexOf instead.

var n = str.indexOf("[]");
like image 193
ephemient Avatar answered Sep 22 '22 14:09

ephemient