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?
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("[]");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With