1252748
1252748

Reputation: 15362

remove everything but alphanumeric and spaces

I have a string that has some special characters and spaces. I can remove the special characters, but how can I make it so it keeps the spaces?

var a = "dent's dc^e co cbs";

var re = /\W/g;

b = a.replace(re, '');

console.log(b);

The way it is, it just deletes everything. And it broke when I tried to add (^\s) after the W

Upvotes: 2

Views: 1627

Answers (2)

s3lph
s3lph

Reputation: 4655

\w doesn't contain numbers. Use this regex: /[^0-9A-Za-z ]/ It matches every char except numbers, capital and non capital letters and the space.

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213193

You can use negated character class with \w, and \s:

var re = /[^\w ]/g;
  • [^\w] gives you same effect as \W
  • Addition of an empty space " " in negated character class, also negates space.

Upvotes: 3

Related Questions