【问题标题】:Remove space before punctuation javascript/jquery删除标点之前的空格 javascript/jquery
【发布时间】:2013-12-01 13:54:42
【问题描述】:

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

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

Output = "This's a test string."

【问题讨论】:

  • 我想要一只小猫。你有问题吗?你试过什么吗?成功了吗?
  • 标点符号是什么意思?您的示例显示了 "Remove the whitespace from the beginning and end of a string" 。为此使用 .trim() 函数
  • 是的,我已经访问了与 rajesh 共享的链接。我只想知道javascript/jquery中的解决方案
  • 我希望 trim fn 不会删除单词或特殊字符之间的空格。

标签: javascript jquery regex


【解决方案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 ?"
.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 只取出空格。
  • 请注意,这也适用于大括号(例如 ( { [);这可能不是您想要的。
【解决方案2】:

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

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

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

【讨论】:

  • str.replace(/\s+(\W)/g, "$1"); 可能更容易。不要尝试将您要定位的字符列入白名单,只使用单词字符以外的任何字符。
  • @ScottSauyet 更简单,但可能不是他们想要的。例如,我认为没有理由删除左括号前的空格。
  • 嗯,您的列表中缺少连字符、括号、问号、分号和其他标点符号。对我来说,标点符号是所有非空格、非单词字符,这很简单。但 OP 似乎不太感兴趣......
  • Anthony Grist 您的回答与 Scoot Sauyet 类似,但具有特定的字符列表。
  • 它在我的场景中很有用,因为我在“P”标签中使用 regx 有时会有 html 文本,例如 -" this 's test cliclk here,/span > 段落”。 Scott Sauyet 解决方案可能没有用。因为该解决方案删除了​​跨度之前的空间,所以输出 HTML 像 - “this's testcliclk here paragarph”。为您的解决方案添加了 +1。
【解决方案3】:

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

/\s\./

用一个点替换它。

【讨论】:

    【解决方案4】:

    尝试替换。

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

    【讨论】:

    • 但@suchithra 他要求删除它们之间的空间。不完全删除's
    【解决方案5】:
    var str= "This 's a test string ."
    
    var regex = /\s\'/i;
    
    var output =str.replace(regex, "'");
    

    【讨论】:

      【解决方案6】:

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

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

      【讨论】:

        【解决方案7】:

        尝试拆分喜欢

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

        看到这个FIDDLE 但首先,尝试一下。

        【讨论】: