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?"
\s+(\W) also removes line feeds. Use / +(\W)/g to take only the spaces out.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');
str.replace(/\s+(\W)/g, "$1");. Don't try to white list the characters you want to target, just use anything but word characters.try replace .
var test = "This's a test string";
test = test.replace(" 's", "'s");
OutPut = test;
'sIf 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," ");
Try to split like
var my_arr = [];
my_arr = my_str.split("'");
var output = $.trim(my_arr[0]) + "'" + $.trim(my_arr[1]);
alert(output);
See this FIDDLE But first of all,Try something.