使用正则表达式删除一个空格字符(JavaScript)

时间:2017-12-10 01:25:28

标签: javascript html regex foreach

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

问题是我需要删除时间和'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>

3 个答案:

答案 0 :(得分:2)

&#13;
&#13;
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
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 1 :(得分:1)

添加您有多种选择

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

答案 2 :(得分:0)

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

(?=.{2}$)匹配空格,后跟(向前看 ?=)两个字符.{2}和字符串结尾$

var s = 'January 7, 2018 @ 10:00 am'

console.log(
  s.replace(/ (?=.{2}$)/g, '')
)