0

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?

1
  • The regex doesn't match your requirement... :) -> regex101.com/r/yY1xP3/1 Commented Feb 1, 2016 at 16:09

6 Answers 6

1

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

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

1 Comment

@erkino: JSFiddle you added was wrong. I corrected it and added again. Thanx for the edit.
1

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

Comments

0

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.

Comments

0

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.

Comments

0

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

2 Comments

Non RE replace() only replaces the first occurence
Added new RegExp, didn't know that replace only replaced the first occurence.
0

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,","));

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.