1

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.

Using "string".replace(/\d+$/, '') I can remove any numbers from the end of the string. However I also need to remove any numbers that have a format with a decimal like #.# or ##.# as well as whole numbers, but only when they appear at the end of the string. From regex101 I have found that the $ is for the end of the string.

I can use .replace(/\d+([.]\d+)?/g) to remove numbers and floats but it removes them from the entire string, not just when they appear at the end, and I can't work out where to put the $ as I don't really understand regex yet and can't get it to work.

It seems such a small and stupid problem but I'd appreciate the help.

Thanks

12
  • 1
    You seem to need .replace(/\d+(?:\.\d+)?$/, '') Commented Jul 13, 2017 at 18:32
  • @WiktorStribiżew thank you, perfect! I don't understand it but it does work, thank you. I will read up more about regex. Commented Jul 13, 2017 at 18:33
  • 1
    There is another /(\d+\.\d+)+$|\d+$/ Commented Jul 13, 2017 at 18:35
  • Why did you accept an answer that doesn't parse int's/decimals correctly ? (?:\d+(?:\.\d*)?|\.\d+)$ .. -1 Commented Jul 13, 2017 at 20:06
  • @sln because I tested it and it worked for me on a live example. Commented Jul 13, 2017 at 20:15

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.