【问题标题】:Remove One Space Character with a Regular Expression (JavaScript)使用正则表达式删除一个空格字符 (JavaScript)
【发布时间】:2017-12-10 01:25:28
【问题描述】:

我需要在一些动态生成的内容中删除一个字符/空格。它是通过我无法更改代码的插件生成的。

问题是我需要删除时间和'am'之间的空格,所以在下面的代码中它是'10.00'和'am'之间的空格。日期和时间由一个函数生成,所以我知道我只需要定位 .datespan 类。

问题是,我今天下午第一次阅读正则表达式,但我似乎无法弄清楚如何做到这一点。我将字符串 .replace() 方法与正则表达式一起使用吗?

我的意思是,说我不知道​​从哪里开始是轻描淡写的。

任何建议或一般性指示都会令人惊叹。

JS

var dateSpan = document.querySelectorAll(".datespan");

dateSpan.forEach(function(item) {

item.replace(
// remove the space character before the 'am' in the .datespan with a regex
// or find a way to always remove the 3rd from last character in a string
)

});

HTML

<span class="datespan">January 7, 2018 @ 10:00 am</span>

【问题讨论】:

    标签: javascript html regex foreach


    【解决方案1】:

    let str = "January 7, 2018 @ 10:00 am"
    str = str.replace(/\sam$/, "am") // replace the space + "am" at the end of the string with "am" (without a space) 
    console.log(str)  // January 7, 2018 @ 10:00am
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

      【解决方案2】:

      增加您的选择范围

      const original = `January 7, 2018 @ 10:00 am`;
      const startStr = original.slice(0, -3);
      const endStr = original.slice(-2);
      const combined = `${startStr}${endStr}`;
      

      【讨论】:

        【解决方案3】:

        您可以使用replace(/ (?=.{2}$)/g, '') 删除字符串末尾的第三个字符。

        (?=.{2}$) 匹配空格后跟(look ahead ?=)两个字符.{2} 和字符串结尾$

        var s = 'January 7, 2018 @ 10:00 am'
        
        console.log(
          s.replace(/ (?=.{2}$)/g, '')
        )

        【讨论】:

          猜你喜欢
          • 2011-11-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-11-20
          • 1970-01-01
          • 1970-01-01
          • 2020-09-03
          • 2023-02-22
          相关资源
          最近更新 更多