Error while trying to use str.search to find the character "+"

I'm trying to search for the character "+" inside a string and I'm getting this error:

error: Uncaught SyntaxError: Invalid regular expression: /+/: Nothing to repeat

This is a sample code to emulate the error I'm experiencing:

var chars1 = 'ABCDEFGHIJLMNOPQRSTUVXZYWK +~!@#$%^&*()';
var char = '+';
var pos = -1;
pos = chars1.search(char);
console.log(pos);

How can I search for these kinds of characters in a string?

Upvotes: 1

Views: 61

Answers (2)

Unmitigated
Unmitigated

Reputation: 89224

If only want to search for text, you can use String#indexOf, which obviates the need to escape regular expression metacharacters.

var chars1 = 'ABCDEFGHIJLMNOPQRSTUVXZYWK +~!@#$%^&*()';
var char = '+';
var pos = -1;
pos = chars1.indexOf(char);
console.log(pos);

Upvotes: 2

scrappedcola
scrappedcola

Reputation: 10572

+ is a special character so you need to escape it. Give this a go:

var chars1 = 'ABCDEFGHIJLMNOPQRSTUVXZYWK +~!@#$%^&*()';
var char = '\\+'; //Yes double \ needed to escape for the search
var pos = -1;
pos = chars1.search(char);
console.log(pos);

For more info check out: https://www.regular-expressions.info/characters.html

Upvotes: 2

Related Questions