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

javascript

Solution

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("[]");

Problem

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?

Original source