Cybernetic
Cybernetic

Reputation: 13334

Remove all special characters except for @ symbol from string in JavaScript

I have a string:

“Gazelles were mentioned by @JohnSmith while he had $100 in his pocket and screamed W#$@%@$!!!!"

I need:

“Gazelles were mentioned by @JohnSmith while he had 100 in his pocket and screamed"

How to remove all special characters from string EXCEPT the @ symbol. I tried:

str.replace(/[^\w\s]/gi, '')

Upvotes: 0

Views: 673

Answers (1)

The fourth bird
The fourth bird

Reputation: 163207

If you want to keep the @ when it is followed by a word char and keeping the W is also ok and also remove the newlines, you could for example change the \s to match spaces or tabs [ \t]

Add the @ to the negated character class and use an alternation specifying to only match the @ when it is not followed by a word character using a negative lookahead.

[^\w \t@]+|@(?!\w)
  • [^\w \t@]+ Match 1+ times any char except a word char, space or tab
  • | Or
  • @(?!\w) Match an @ not directly followed by a word char

Regex demo

In the replacement use an empty string.

Upvotes: 2

Related Questions