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

Remove space before punctuation javascript/jquery

本文关键字:空格 jquery 标点符号 javascript 删除      更新时间:2023-09-26

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

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

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

var regex = /'s+([.,!":])/g;
var output = "This 's a test string .".replace(regex, '$1');

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

/'s'./

并仅用一个点替换它。

尝试替换 。

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," ");

尝试

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

看到这个小提琴 但首先,尝试一些东西。