Skip to content Skip to sidebar Skip to footer

Removing Int And Float From The End Of A String Using Javascript Regex

I found an answer in this question that is almost perfect but I need a slight tweak. I've read the basics of regex and I'm using https://regex101.com/ but I can't figure it out. Us

Solution 1:

You may use

.replace(/\d+(?:\.\d+)?$/, '')

The pattern matches

  • \d+ - one or more digits
  • (?:\.\d+)? - a non-capturing group (the ?: makes it non-capturing, that is, you cannot access the value captured by this group) that matches an optional sequence of a . and then 1+ digits
  • $ - end of string.

To also remove any 0+ whitespaces before the number, add \s* (where \s matches any whitespace and * quantifier makes the regex engine match (consecutively) 0 or more of the characters matched with this pattern) at the pattern start.

See the regex demo.

Post a Comment for "Removing Int And Float From The End Of A String Using Javascript Regex"