If you try to find strings such as " []" or " ()" using a function search(), this will not work.
[]
()
search()
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.
-1
0
Why is this?
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("[]");
, . , search new RegExp.
search
new RegExp
, str.search("[]"), str.search(/[]/) ( , -1).
str.search("[]")
str.search(/[]/)
, str.search("()"), str.search(/()/) ( "" 0).
str.search("()")
str.search(/()/)
""
MDN, W3Schools.
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
"[]" "()" . :
str.search("\\[\\]")
, :
str.indexOf("[]")
Source: https://habr.com/ru/post/1675937/More articles:Предпочтительный шаблон для того, чтобы обойти "перемещение из заимствованного я" - oopKrbException connecting a Hadoop cluster with a Zookeeper client - UNKNOWN_SERVER - hadoopDoes passing a whole block of data into a function or just a few columns matter in terms of computational speed? - parameter-passingВыполнение задач параллельно в powershell - foreachCryptogenic Tool Error in Hyperledger Fabric - hyperledgerRecursive node tree search - javascriptReact-native: function call when returning from scene - javascriptDownload a file using jquery, a common handler and wait state - jqueryUnprepared (in promise) TypeError: Fetch to Fetch - In Employee when disconnected - gitggplot2 geom_area edges are not vertical - rAll Articles