最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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 - .asp?filename=tryjsref_search

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

Why is that?

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./jsref/tryit.asp?filename=tryjsref_search

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

Why is that?

Share Improve this question asked Apr 28, 2017 at 17:26 kaushalkaushal 81514 silver badges28 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

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

The JavaScript search function takes a regular expression as its argument:

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

In regular expressions, "[" and "(" are special characters.

Try replacing your function with this:

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

or better:

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

The '[' special character is escaped. Once that is escaped, the ']' does not need to be escaped because it is only treated special after an unescaped '['.

For more information about regular expressions in JavaScript, look here:

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

It's because search is expecting a regular expression. If a string is passed, then search will explicitly transform it into a regexp using new RegExp.

Calling it like str.search("[]") is like calling it str.search(/[]/) (nothing in the string matches an empty set so -1 is returned).

And calling it like str.search("()") is like calling it str.search(/()/) (the first empty string "" is found at the index 0).

I remend looking for the docs on MDN not W3Schools.

Because the search string is a regular-expression and "[]" and "()" are both magic. You need to double-escape them:

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

Or even better, as ephemient points out:

str.indexOf("[]")
发布评论

评论列表(0)

  1. 暂无评论