Removing dynamic content from the end of a string

Viewed 56

I need to remove any zero values from the end of a string. There could be no matches, or there could be several matches. Some examples:

10d 5h 0m 0s would become 10d 5h

10d 5h 10m 0s would become 10d 5h 10m

10d 0h 0m 0s would become 10d

I toyed with the following regex:

(0h)?\s(0m)?\s(0s)$

But it only matches the first and third example. What am I doing wrong?

3 Answers

What about using split()

function removeZeros(string) {
  return string.split(/(\s|\b)0/)[0];
}

console.log(removeZeros('10d 5h 0m 0s'));
console.log(removeZeros('10d 5h 10m 0s'));
console.log(removeZeros('10d 0h 0m 0s'));
console.log(removeZeros('0s'));

/(\s?\b0[hms])+$/g seems to match your spec. Start with an optional space and word boundary and match 0 followed by one of h, m or s, one or more times, anchored at the end of the string. Replace with the empty string.

const p = /(\s?\b0[hms])+$/g;

[
  "10d 5h 0m 0s",  // => "10d 5h"
  "10d 5h 10m 0s", // => "10d 5h 10m"
  "10d 0h 0m 0s",  // => "10d"
  "0s",            // => ""
  "10d 0m 2s",     // => "10d 0m 2s"
].forEach(e => console.log(`'${e}' => '${e.replace(p, "")}'`));

Just my two cents:

(\s0h)?(\s0m)?(\s0s)$
Related