JavaScript: String.search () cannot search for "[]" or "()"

If you try to find strings such as " []" or " ()" using a function search(), this will not work.

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

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

The search []returns -1, and the search ()returns 0. Is always.

Why is this?

+4
source share
4 answers

String.search uses RegExp , and converts its argument to one, if not already. []and ()are special characters for RegExp.

:

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

, String.indexOf.

var n = str.indexOf("[]");
+3

, . , search new RegExp.

, str.search("[]"), str.search(/[]/) ( , -1).

, str.search("()"), str.search(/()/) ( "" 0).

MDN, W3Schools.

+2

JavaScript :

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search

"[" "(" .

:

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

:

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

'[' . , , '' ' , unescaped' ['.

JavaScript . :

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

+1

"[]" "()" . :

str.search("\\[\\]")

, :

str.indexOf("[]")
0

Source: https://habr.com/ru/post/1675937/


All Articles