Paul Fitzgerald
Paul Fitzgerald

Reputation: 12129

remove special characters from a string if they are on their own and not part of a word

I am trying to remove special characters from a string if they are on their own and not part of a word.

example would be

var str = "This i$ @ gr£@t t£$t !: i think i$nt it%";

should become

var newstr = "This i$ gr£@t t£$t i think i$nt it%";

Upvotes: 0

Views: 75

Answers (2)

Aran-Fey
Aran-Fey

Reputation: 43166

You can use this pattern:

^[^\w\s]+\B\s*|\s+[^\w\s]+\B(\s)\s*|\s*\B[^\w\s]+$

Substitute with $1. This will collapse the whitespace around the removed word into a single space.

Demo.

Downside: if you aren't happy with which characters are considered "special characters", you have to modify all three occurences of the character class [^\w\s].

Upvotes: 0

Shafizadeh
Shafizadeh

Reputation: 10340

Use this pattern:

var str = "This i$ @ gr£@t t£$t !: i think i$nt it%";
var result = str.replace(/(?:^|\s+)\W+(?:\s+|$)/g," ");
document.write(result);

Upvotes: 4

Related Questions