Joe
Joe

Reputation: 4234

Replacing, regex, javascript

Got this string:

'test',$, #207

I need to remove spaces which have a commma before

So the result will be: 'test',$,#207

Tried this:

  replace(/\/s,]/g, ',')

Not working. Any ideas?

Upvotes: 0

Views: 58

Answers (6)

user2705585
user2705585

Reputation:

To replace only spaces and not other whitespaces use the following regex.

Regex: /, +/g

Explanation:

, will search for comma.

+ will search for multiple spaces.

And then replace by , using replace(/, +/g, ',')

Regex101 Demo

JSFiddle demo

Upvotes: 1

dexhering
dexhering

Reputation: 422

For all whitespaces which have a "," before

var str = "test,$, #207,  th,     rtt878";
console.log(str.replace(/\,\s+/g,","));
var str = "test,$, #207";
console.log(str.replace(/\,\s+/g,","));

Upvotes: 0

seahorsepip
seahorsepip

Reputation: 4809

replace(new RegExp(find, ', '), ',');

Upvotes: 0

Edson Horacio Junior
Edson Horacio Junior

Reputation: 3143

I think you meant comma that have whitespace afterwards:

stringVar = "'test',$, #207";
replace('/\,\s/g', stringVar);

\, means , literally and \s means whitespace.

You can test javascript regex and know a little more about the modifiers and stuff at regex101.

Upvotes: 0

Gilgamesh
Gilgamesh

Reputation: 668

Since your pattern is simple you can just do this .split(', ').join(',')

Upvotes: 1

Christoph Burschka
Christoph Burschka

Reputation: 4689

I need to remove spaces which have a commma afterwards

No, your example says the opposite. That is, you want to remove spaces that have a comma before them.

In either case, the error in your expression is the "]".

replace(/\/s,/g, ',')

Does what you say you want to do, and

replace(/,\/s/g, ',')

Does what the example says.

The other answer is right, though - just use replace(' ,', ''); you need no regex here.

Upvotes: 0

Related Questions