0

I am using in string.search("value") to search string. It give SyntaxError: Invalid regular expression: /[sanofi-aventis]/: Range out of order in character class. Below is my code and screenshot.

var str = "[sanofi-aventis]";
var res = str.search("[sanofi-aventis]");

enter image description here

Naisarg Parmar
  • 759
  • 8
  • 25
  • `String.prototype.search()` expects a regular expression as a parameter, not a substring. Why do you need `.search()`? – Ivar Jun 14 '21 at 13:28
  • I want to search value(e.g. "[sanofi-aventis]" ) from name(e.g "[sanofi-aventis]") – Naisarg Parmar Jun 14 '21 at 13:31
  • What does "search" mean in this context? Whether a substring exists in the string? If so: [How to check whether a string contains a substring in JavaScript?](https://stackoverflow.com/questions/1789945/how-to-check-whether-a-string-contains-a-substring-in-javascript) – Ivar Jun 14 '21 at 13:33
  • @Ivar thank you for reply..but below is the correct answer and substitute of search() – Naisarg Parmar Jun 14 '21 at 13:41
  • this is normal in my opinion because `[sanofi-aventis]` is not a good RegExp. – snd Jun 14 '21 at 13:42
  • Does this answer your question? [JavaScript search() fails to find "()"](https://stackoverflow.com/questions/3977351/javascript-search-fails-to-find) – Ivar Jun 14 '21 at 13:48
  • @Ivar yes I understood the internal working of search(). thank you once again for you concern – Naisarg Parmar Jun 14 '21 at 13:51

1 Answers1

3

That is because String.prototype.search only accepts a regular expression as an argument, not a string. Your string you provided is an invalid regex. If you want to find it it exists, then just use String.prototype.indexOf() or String.prototype.includes:

var str = "[sanofi-aventis]";

// If value is not -1 then substring exists
console.log(str.indexOf("[sanofi-aventis]") !== -1);  // true
console.log(str.indexOf("foo bar") !== -1);  // false

// Uses ES6 String.prototype.includes, which returns a boolean
console.log(str.includes("[sanofi-aventis]"));  // true
console.log(str.includes("foo bar"));  // false

A little further info on why [sanofi-aventis] throws a range error: that is because it is interpreted as a regex pattern, and the part i-a throws the error since the dash between the two square brackets indicates a character range. Since i comes after a in the charset, it is invalid.

You will realize that [sanofa-iventis] will not throw an error, since a-i is a valid character range. However using this in String.prototype.search will not yield the result you expected.

Terry
  • 63,248
  • 15
  • 96
  • 118