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."
"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?"
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With