Russell Christopher
Russell Christopher

Reputation: 1707

Regex: Replace Parentheses in JavaScript code with Regex

Need to remove spaces, single quotes, and parens from a string displayed in as an <li>

This works great for the first two:

var foo = li.replace(/\s|\'+/g, "");

I assumed all I needed to do was add another few ORs to this, escaping the ( or ) symbols to search for them:

var foo = li.replace(/\s|\'+/g|\(|\), "");

Compiler no likey:

Uncaught SyntaxError: Unexpected token ILLEGAL 

It appears the the that the open and closing paren are getting evaluated anyway - even with the escape symbols. What am I doing wrong here? Thanks!

Upvotes: 0

Views: 115

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

You don't have the right syntax for regex literals. They're written as

/pattern/flags

And what you seem to want isn't a bunch of OR but a character class.

Use

var foo = li.replace(/[\s'()]+/g, "");

Upvotes: 2

Related Questions