Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove space before punctuation javascript/jquery

I want to remove space before every punctuation in Javascript/jquery. For example

Input string = " This 's a test string ."

Output = "This's a test string."
like image 683
Venkat Avatar asked Mar 21 '23 14:03

Venkat


2 Answers

"This string has some -- perhaps too much -- punctuation that 's not properly "
+ "spaced ; what can I do to remove the excess spaces before it ?"
.replace(/\s+(\W)/g, "$1");

//=> "This string has some-- perhaps too much-- punctuation that's not properly "
//   + "spaced; what can I do to remove the excess spaces before it?"
like image 122
Scott Sauyet Avatar answered Mar 24 '23 05:03

Scott Sauyet


Use the String.replace function with a regular expression that will match any amount of whitespace before all of the punctuation characters you want to match:

var regex = /\s+([.,!":])/g;

var output = "This 's a test string .".replace(regex, '$1');
like image 23
Anthony Grist Avatar answered Mar 24 '23 05:03

Anthony Grist