简体   繁体   English

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

[英]Remove One Space Character with a Regular Expression (JavaScript)

I need to remove one character / space in some dynamically generated content. 我需要在一些动态生成的内容中删除一个字符/空格。 It's generated via a plugin that I can't change the code of. 它是通过我无法更改其代码的插件生成的。

The problem is I need to remove the space between the time and the 'am', so in the code below it's the space between the '10.00' and the 'am'. 问题是我需要删除时间和“ am”之间的空格,因此在下面的代码中,它是“ 10.00”和“ am”之间的空格。 The date and time are generated by one function, so I know I will only have to target the .datespan class. 日期和时间是由一个函数生成的,所以我知道我只需要定位.datespan类。

The problem is, I've been reading up on regex for the first time this afternoon and I can't seem to work out how to do this. 问题是,我今天下午第一次阅读了正则表达式,但似乎无法解决该问题。 Will I use the string .replace() method with a regex? 我会在正则表达式中使用字符串.replace()方法吗?

I mean, to say I don't know where to start with this is an understatement. 我的意思是说我不知道​​从何开始。

Any advice or general pointers would be amazing. 任何建议或一般指针将是惊人的。

JS 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 HTML

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

 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; } 

To add to the variety of choices you have 为了增加您的选择范围

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

You can remove the third character from the end of string using replace(/ (?=.{2}$)/g, '') . 您可以使用replace(/ (?=.{2}$)/g, '')从字符串末尾删除第三个字符。

(?=.{2}$) matches the white space followed by (with look ahead ?= ) two characters .{2} and end of string $ (?=.{2}$)与空白匹配,后跟( 向前看 ?= )两个字符.{2}和字符串$的结尾

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM