0

I am trying to write a CSS minifier script for fun and I now want to create a function that removes any unnecessary 0.x with only .x. So for example this string:

attribute:0.12% 10.123% 0.1%

Should turn into:

attribute:.12% 10.123% .1%

I tried to use a simple replace like this: .replaceAll(':0.', ':.') but this doesn't work for the case when the number stands alone like the 0.1% does in my example.

I am not very good with regular expressions but I guess that is what I need. So basically I want to find all numbers that match the format 0. but DON'T have a number immediately to the left of them (like in the case 10.123%) and replace it with ..

eligolf
  • 1,682
  • 1
  • 6
  • 22

1 Answers1

0

Exactly this:

So basically I want to find all numbers that match the format 0. but DON'T have a number immediately to the left of them (like in the case 10.123%) and replace it with

This pattern checks for a 0 followed by a dot (0.), but only if there isn't a digit immediately to the left of the 0.

const input = 'attribute:0.12% 10.123% 0.1%';
const regex = /(?<!\d)0\./g;
const output = input.replace(regex, '.');

console.log(output); // attribute:.12% 10.123% .1%
Lars Flieger
  • 2,421
  • 1
  • 12
  • 34
  • Thank you, precicely what I needed! Any good source where I can learn these cryptic things from? :) – eligolf Mar 22 '23 at 14:34
  • @eligolf If you want to learn js and regex try: https://www.freecodecamp.org/ It's interactive, very good described and fun to do! – Lars Flieger Mar 22 '23 at 14:36
  • 1
    *Any good source where I can learn these cryptic things from* - keeping to SO, the so [tag:regex] is a good place to start - links to the [regex SO wiki](https://stackoverflow.com/tags/jquery/info) (via learn more...) which includes many resource and links to the [SO regex reference question](https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) which provides a fine reference - though possibly a little more than overwhelming - it is a reference page rather than a tutorial. – freedomn-m Mar 22 '23 at 14:41
  • 1
    I also have no idea. Answer is well formatted, quoting the issue and providing a snippet. Sometimes people think they've answered in the comments so downvote (I've seen comments like "as I said 2 hours ago" referring to a comment) - but comments *are not answers*. – freedomn-m Mar 22 '23 at 16:42