我想在Javascript/jquery中删除每个标点符号前的空格。例如:
Input string = " This 's a test string ."
Output = "This's a test string."
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)
也会移除换行符。使用 / +(\W)/g
只取出空格。 - Marco LackovicString.replace
函数与一个正则表达式匹配所有空格符号,并匹配您想要匹配的所有标点符号之前的任何数量:var regex = /\s+([.,!":])/g;
var output = "This 's a test string .".replace(regex, '$1');
str.replace(/\s+(\W)/g, "$1");
。不要尝试列出您想要定位的字符的白名单,只需使用除单词字符以外的任何字符即可。 - Scott Sauyet尝试替换。
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, "'");
replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"")
replace(/\s{2,}/g," ");
我的完整示例:
var s = "This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation";
var punctuationless = s.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"");
var finalString = punctuationless.replace(/\s{2,}/g," ");
/\s\./
并将其替换为一个点。
var my_arr = [];
my_arr = my_str.split("'");
var output = $.trim(my_arr[0]) + "'" + $.trim(my_arr[1]);
alert(output);
看看这个FIDDLE。但首先,试一下。