Javascript search for a special character

I am struggling for hours with my flow.
Last part is to search for a [ sign in a variable and if not add it
I made a simple test, but still get errors
"SyntaxError: Invalid regular expression: /[/: Unterminated character class"

script
var str = "{dit is een test}";
var n = str.search("[");

if (n !== -1)
{
msg.a = "aap"
}
else
{
msg.a = "noot"
}
return msg;

As it states your search criteria isn't a regular expression.

Use string.includes instead...

https://www.w3schools.com/jsref/jsref_includes.asp

Perhaps better use string.indexOf() instead. This will give you the position of your search string.
But as you are looking only for the existence the other solution will work too (but the result is a boolean value!)

Hallo Peter,
Om bovenstaande samen te vatten: str.search maakt gebruik van regex: regular expressions. str.indexOf/str.includes is een gewone zoekvorm, zoals je waarschijnlijk wilt.
Regex wordt eigenlijk pas interessant als je op zoek bent naar specifieke combinaties. Daar komt bij dat het niet de meest leesbare taal is, die bovendien gebruik maakt van speciale tekens voor zoekopdrachten. Bijvoorbeeld het haakje waar je naar zoekt betekent in regex de start van een blok van toegestane tekens. En de error in je post geeft dan ook aan dat dit blok niet wordt gesloten. Voorlopig niets om je zorgen over te maken, gebruik de andere functies die genoemd worden, regex is hier niet nodig.
M.v.g,
Lena

—————
To summarise the above posts, str.search uses regex, and in regex the brackets have a special meaning. Rather than searching for the exact character “[“ it will open a block of allowed characters, one that is never closed and thus gives the error. The other functions mentioned, includes and indexOf do the actual text search you think str.search does. So use either of those for your needs.

Thanks to you all!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.