I have a string with multimple whitespaces between words and I want to reduce all the whitespace to just one.And after to delete the whitespace before and after[',','.','?','!'] and let one space after ','. Can you help me with a code?
Asked
Active
Viewed 935 times
-2
-
So basically: "How do I remove spaces from a string?" – Stephan Bijzitter Jan 20 '17 at 08:11
-
Possible duplicate of [How to replace all occurrences of a string in JavaScript?](http://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) – Stephan Bijzitter Jan 20 '17 at 08:11
-
@StephanBijzitter: Well, as per the current question version, it is not. – Wiktor Stribiżew Jan 20 '17 at 08:13
-
Well, now, it is just a duplicate/off-topic. Please don't change your requirements, or just post a new question. – Wiktor Stribiżew Jan 20 '17 at 08:24
1 Answers
1
Your approach does not work because you only escape the first space in your newSeparators
, while .
and ?
remain special regex metacharacters, and /\ . /
regex matches a space, any char, a space, and /\ ? /
will match an optional space and 1 space after.
I suggest using:
/\s*([.!:?])\s*|\s*(,)\s*/g
See the regex demo.
Details:
\s*
- 0+ whitespaces([.!:?])
- Group 1 capturing.
,!
,:
or?
\s*
- 0+ whitespaces|
- or\s*(,)\s*
- a,
in between 0+ whitespaces captured into Group 2.
var newSeparators = /\s*([.!:?])\s*|\s*(,)\s*/g;
var data = "word, word . word ! word ? word";
data = data.replace(newSeparators, function($0, $1, $2) {
return $2 ? $2 + " " : " " + $1 + " ";
});
console.log(data);

Wiktor Stribiżew
- 607,720
- 39
- 448
- 563
-
Yes thanks but I have one more issue.The data I want to format is a long text and is not all the time of this type: word , word . word ! word ? word . Sometimes I have : word, word and I want to have just one white space between seperators.The code will make word , word(with 2 whitespace after comma) – S. Georgian Jan 20 '17 at 08:05
-
Yes, and what is the problem? Post the text and explain what is different from your sample input. It is not clear what you mean, sorry. Right now, this solution resolves the issue in the original post. – Wiktor Stribiżew Jan 20 '17 at 08:06
-
Thanks I can have the result that I want with this code If I format it a little bit. – S. Georgian Jan 20 '17 at 08:36