简体   繁体   中英

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'. The date and time are generated by one function, so I know I will only have to target the .datespan class.

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?

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

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>

 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, '') .

(?=.{2}$) matches the white space followed by (with look ahead ?= ) two characters .{2} and end of string $

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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