admin管理员组

文章数量:1355559

I have a date formatted like such:

04/09/2024 10:45

I am trying to remove leading zeros when they exist in the month and day. I have been trying to do this with regex but am struggling to get the outcome I want

dateString = dateString.replace(/0*\//g, '')

Can someone point me in the right direction or if there is a simpler way to do this please let me know!

I have a date formatted like such:

04/09/2024 10:45

I am trying to remove leading zeros when they exist in the month and day. I have been trying to do this with regex but am struggling to get the outcome I want

dateString = dateString.replace(/0*\//g, '')

Can someone point me in the right direction or if there is a simpler way to do this please let me know!

Share Improve this question edited Mar 28 at 16:59 Mister Jojo 22.5k6 gold badges25 silver badges44 bronze badges asked Mar 28 at 16:25 D. FowlerD. Fowler 132 bronze badges 5
  • 2 I suspect it would be easier to simply parse the string into an actual Date object and then format it however you like. Did you try that? (Edit: obligatory) – David Commented Mar 28 at 16:29
  • 1 You might look into DateTimeFormat using dateStyle: "short" – mykaf Commented Mar 28 at 16:29
  • 4 Agreed. the JS DateTime interface is the tool for the job here - you can input a date in one format, and output it in another. And it's designed specifically to work with all the many wonderful weirdnesses of dates, rather than regex which is a far more general text manipulation tool. – ADyson Commented Mar 28 at 16:29
  • duplicate: Remove leading zeroes in datestring. – pilchard Commented Mar 31 at 9:18
  • also: How to replace 0 zeros only in date and month using regex or move zeros from Date string or the canonical How do I format a date in JavaScript? – pilchard Commented Mar 31 at 9:20
Add a comment  | 

6 Answers 6

Reset to default 3

I would split by a /, and attempt to parse each piece as a number:

const str = "04/09/2024 10:45"
const result = str.split("/").map(e => +e || e).join("/")
console.log(result)

I agree with what JDB wrote.
Using regular expressions isn't always the best idea.

It's better to parse your date string and recompose it.

I suggest this solution:
And there's even a little regExp to keep you happy ;)

const dateClearing = dte =>
  {
  let [M,D,Y,h,m] = dte.match(/\d+/g);
  return `${+M}/${+D}/${Y} ${h}:${m}`;
  }

console.log( dateClearing('04/09/2024 10:45') ); // 4/9/2024 10:45
console.log( dateClearing('04/09/2024 10:05') ); // 4/9/2024 10:05
console.log( dateClearing('04/09/2024 09:00') ); // 4/9/2024 09:00

There is an old addage which is as incorrect as it is useful:

Some people, when confronted with a problem, think “I know, I’ll use regular expressions.” Now they have two problems.

It is incorrect because regular expressions, when used correctly, are extremely powerful and can solve a wide range of challenging problems.

It is useful because very few people understand regular expressions well enough to know what they CAN'T do, and when they SHOULDN'T be used.

That said, here's a simple regex that will give you the results you requested for the input you've given. (That last bit can't be emphasized strongly enough.)

"04/09/2024 10:45".replaceAll(/\b0/g, "")

// 4/9/2024 10:45

\b matches a word boundary (either the beginning or end of a word, but never in the middle, where "word" means an alpha-numeric block of text)

So this will match a 0 which is preceded by a non-alpha-numeric character.

HOWEVER... I don't know all the other inputs you might be dealing with, so use this expression with caution. It's very likely you have other inputs you've not shared which will result in unexpected behavior.

For example...

"04/09/2024 10:05".replaceAll(/\b0/g, "")

// 4/9/2024 10:5

You probably didn't intend to remove the leading zero in the minutes part.

So I recommend that you follow the advice in the comments and PARSE your date string, then re-format however you want.

For example, using DateTimeFormat...

const formatter = Intl.DateTimeFormat("en-US", {
  month: "numeric",
  day: "numeric",
  year: "numeric",
  hour: "numeric",
  minute: "2-digit",
});

// ...

let dateString = "04/09/2024 10:05";
// -----------------------------------------------------------------------------
// Fill in your own parse logic. Date.parse() will give you an answer, but if
// you aren't using one of the ECMA-262 formats, then the result isn't very
// trustworthy.
const dateTime = Date.parse(dateString); // WARNING: this is notoriously sketchy
// -----------------------------------------------------------------------------
dateString = formatter.format(dateTime);
// dateString = "4/9/2024, 10:05 AM"

Note that since your date time string is not in a standard format, results of parsing it can vary between time zones and browsers.

I'd suggest avoiding parsing to Date as it's an unnecessary complication. Just trim leading zeros from the first to numeric values by converting to number before reformatting as a string. So no regular expression either.

// Trim leading zeros from dates of format dd/dd/yyyy hh:mm
// "/" character must only be used as date separator.
let trimZeros = (d) => {
  let [a, b, rest] = d.split('/');
  return `${+a}/${+b}/${rest}`;
}

// Some tests - not exhuastive
['04/09/2024 10:45',
 '10/01/2000 00:00',
 '07/10/2000 01:50',
 ]
 .forEach(s => console.log(trimZeros(s)));

Kindly check with given regex hopefully it should work

dateString = dateString.replace(/\b0(\d)\b/g, '$1');

If you are interested in performance, please manipulate the string manually. When you format a lot of dates you will notice much better performance:

const format = str => {
  let prev = '';
  let out = '';
  for(let i = 0; i < str.length; prev = str[i], i++){
    if((!prev || prev === '/') && str[i] === '0') continue;
    out += str[i];
  }
  return out;
}

console.log( format('04/09/2024 10:45') ); // 4/9/2024 10:45
console.log( format('04/09/2024 10:05') ); // 4/9/2024 10:05
console.log( format('04/09/2024 09:00') ); // 4/9/2024 09:00

本文标签: javascriptRemove Leading 0s from Date Formatted mmddyyyyStack Overflow