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.