在标点符号javascript / jquery之前删除空格

时间:2013-11-18 12:05:37

标签: javascript jquery regex

我想在Javascript / jquery中的每个标点符号之前删除空格。例如

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

Output = "This's a test string."

7 个答案:

答案 0 :(得分:4)

"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?"

答案 1 :(得分:2)

String.replace函数与正则表达式一起使用,该表达式将匹配您要匹配的所有标点符号前的任意数量的空格:

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

var output = "This 's a test string .".replace(regex, '$1');

答案 2 :(得分:0)

尝试拆分,如

var my_arr = [];
my_arr = my_str.split("'");
var output = $.trim(my_arr[0]) + "'" + $.trim(my_arr[1]);
alert(output);

请参阅此FIDDLE但首先,尝试一下。

答案 3 :(得分:0)

如果您想使用正则表达式,请匹配

/\s\./

并用一个点替换它。

答案 4 :(得分:0)

尝试替换。

var test = "This's a test string";
test = test.replace(" 's", "'s");
OutPut = test;

答案 5 :(得分:0)

var str= "This 's a test string ."

var regex = /\s\'/i;

var output =str.replace(regex, "'");

答案 6 :(得分:0)

如果您想从字符串中删除特定标点符号,最好明确删除您想要的内容

   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," ");
相关问题