0

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, '')
11
  • Add an @ to the character class [^\w\s@] Commented Feb 29, 2020 at 15:36
  • Thank you. I also have sentences with the ↵ symbol, which isn't getting removed. Commented Feb 29, 2020 at 15:38
  • 1
    Do you want to keep the @ only when it is followed by a word char? (?:[^\w\s@]+|@(?!\w)) Commented Feb 29, 2020 at 15:40
  • 1
    So I'd go with: @(?!\w)|[^\w\s@] for example. Pretty much what @TheFourthBird mentioned earlier. Commented Feb 29, 2020 at 15:48
  • 1
    That is because the \s in the negated character class makes it not match a newline. It could be like this for example [^\w \t@]+|@(?!\w) regex101.com/r/2fM0LK/1 Commented Feb 29, 2020 at 15:54

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.