1

With

var str = "sdsdTheoDefi[0]sdsds";
console.log(str.search("\[0"));

the JavaScript hangs

However

var str = "sdsdTheoDefi[0]sdsds";
console.log(str.search("\[0\]"));

Works fine.

Obviously any editor finds [0 in sdsdTheoDefi[0]sdsds meaning the JavaScript search function works different to standard regular expression.

How can I make this simple search with the JavaScript search function?

function myFunction() {
  var str = "sdsdTheoDefi[0]sdsds";
  var n = str.search("\[0\]");
  document.getElementById("demo").innerHTML = n;
}
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Why not just `var n = str.indexOf("[0");` – mplungjan Jun 27 '19 at 08:24
  • [Why do regex constructors need to be double escaped?](https://stackoverflow.com/questions/17863066/why-do-regex-constructors-need-to-be-double-escaped) explains it all. It is an extremely common, frequent issue. – Wiktor Stribiżew Jun 27 '19 at 08:31
  • @mplungjan, the character [ is used in regular expressions to start a category of characters that must ends with ], so there it is a not well formed regular expression. – Carlos Freites Jun 27 '19 at 13:16
  • I know. I do not see the need for a regex at all – mplungjan Jun 27 '19 at 13:17
  • Oh! The problem is the function String.search, it assumes the search string (the needle) is a regular expression. There is no option to avoid that. There is no way in my program to know in advance if the needle will be simple or complex. And parsing the needle is too complicated. – Carlos Freites Jun 27 '19 at 17:16
  • IndexOf does not care – mplungjan Jun 28 '19 at 06:21

2 Answers2

3

You're passing a string to search. See the docs:

A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj).

Remember that \ has special meaning in a string literal:

var n = "\[0"
console.log(n);

So you end up creating a regular expression that has a [ with no matching ].


Avoid new RegExp(obj) as it is more trouble than it is worth most of the time (it's unavoidable if you need to construct regex with variables, but that isn't the case here).

Use a regex literal instead:

var str = "sdsdTheoDefi[0]sdsds"; 
var n = str.search(/\[0/);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thanks a lot. I would never realize that by myself. My program now works fine. Wuauuu "\\[0\\]" works because it is a valid regular expression. Thanks again. – Carlos Freites Jun 27 '19 at 08:36
0

String.prototype.search expects a regular expression:

function myFunction() {
  var str = "sdsdTheoDefi[0]sdsds";
  var n = str.search(/\[0/);
  document.getElementById("demo").innerHTML = n;
}
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79