【问题标题】:Delete a specific repeated character in javascript删除javascript中的特定重复字符
【发布时间】:2014-04-08 13:06:37
【问题描述】:

我看到了以下问题Regex to remove a specific repeated character,它与我的非常相似(如果不准确的话),但它是在 C# 中实现并使用该语言的字符串方法。

我想知道是否有人可以提出javascript 的实现?

如果你有示例

what---is-your-name- => what-is-your-name

---what-is----your-name-- => what-is-your-name

那么如何去除特定字符的重复出现,在本例中为- 并在javascript 中只用一个- 替换它?

【问题讨论】:

  • Regex.Replace(inputString, "-+", "") 变为 inputString.replace(/-+/g, "")Trim 变为 trimvars 按原样工作。

标签: javascript regex slug


【解决方案1】:

应该这样做:

 var newValue = value.replace(/-+/g, '-');

您提供的示例与您对问题的描述相矛盾,因为您似乎想删除开头和结尾的所有连字符。如果是这样,这将做到:

 var newValue = value.replace(/^-+|-+$/g, '').replace(/-+/g, '-');

【讨论】:

    【解决方案2】:
    "what---is-your-name-".replace(/\-+/g, '-');
    

    【讨论】:

      【解决方案3】:

      类似的东西

      var str = "---what---is-your----name-----";
      var res1 = str.replace(/^-+/,'');
      console.log(res1);
      var res2 = res1.replace(/-+$/,'');
      console.log(res2);
      var res3 = res2.replace(/-+/g,'-');
      console.log(res3);
      

      或者您可以简单地将所有条件合二为一,形成一条线

      str.replace(/^-+|-+$|-+/g,'-');
      

      【讨论】:

      • 我将这些行分开,以便更清楚地了解它是如何发生的
      【解决方案4】:

      使用这个正则表达式

      .replace(/\-+/g,'-').replace(/^-|-$/g, '');
      

      【讨论】:

        【解决方案5】:

        这是一个变体答案,它只使用一个正则表达式和一个对String.replace 的调用;其他答案仍然适用。

        s = s.replace(/^-*|-*$|(-)-*/g, "$1");
        

        所以:

        s = "---what-is----your-name--";
        s = s.replace(/^-*|-*$|(-)-*/g, "$1");
        // s == what-is-your-name
        

        解释:

        ^-*    // match any number of dashes at the start
        -*$    // match any number of dashes at the end
        (-)-*  // match one or more dashes, capturing one dash in 1st group
        
        /g     // match globally/repeatedly
        
        "$1"   // replace with 1st group value;
               // so it will replace with "-" or "" (for undefined capture)
        

        【讨论】:

          【解决方案6】:

          一口气:

          str.replace(/^-+|-+(?=-|$)/g, '')
          

          解释:

          (?=..) 是一个前瞻断言,表示跟随。它只是一个检查,不是匹配结果的一部分。

          关于-+(?=-|$):

          由于默认情况下量词是贪婪的,-+ 匹配字符串的一部分中的所有-,因此先测试了前瞻:两种可能的情况

          我。部分在字符串中间:hello-----world

          因为在前瞻失败并且正则表达式引擎返回一个字符后只有一个w。现在-+ 只匹配四个-,后面跟着一个-,即前瞻成功。由于它不是匹配的一部分,最后一个- 不会被替换函数删除。

          二。该部分在字符串的末尾:world-----

          -+ 匹配所有- 直到字符串结尾和前瞻断言成功的第二部分。所有- 都被替换功能删除。

          注意(?=-|$)(后面跟一个破折号或者字符串的结尾)也可以写成(?![^-])(后面不能跟任何不是破折号的字符) 以避免交替。是一样的,但是用否定的方式表达。

          【讨论】:

          • 你能告诉我积极的前瞻是如何工作的吗?
          • @aelor:我已经添加了描述。
          猜你喜欢
          • 2012-10-21
          • 2021-08-15
          • 1970-01-01
          • 1970-01-01
          • 2018-09-16
          • 1970-01-01
          • 2012-03-08
          • 2016-08-30
          • 1970-01-01
          相关资源
          最近更新 更多