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."
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 want to use regular expressions, then match on
/\s\./
and replace it with just a dot.
try replace .
var test = "This's a test string";
test = test.replace(" 's", "'s");
OutPut = test;
var str= "This 's a test string ."
var regex = /\s\'/i;
var output =str.replace(regex, "'");
If you want to remove specific punctuation from a string, it will probably be best to explicitly remove exactly what you want like
replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"")
Doing the above still doesn't return the string as you have specified it. If you want to remove any extra spaces that were left over from removing crazy punctuation, then you are going to want to do something like
replace(/\s{2,}/g," ");
My full example:
var s = "This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation";
var punctuationless = s.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"");
var finalString = punctuationless.replace(/\s{2,}/g," ");