-3

I want to allow input in a text box only if it is a number, a decimal point or a backspace.

I have the following regex that matches numbers or the decimal point. How can I also accept a backspace? I know [\b] matches the backspace but I'm having trouble adding it to my existing set.

/^[0-9\.]+$/
noclist
  • 1,368
  • 1
  • 18
  • 46
  • I want to allow input in a text box only if it is a number, a decimal point or a backspace. – noclist Sep 03 '20 at 15:13
  • `\b` does not match backspace, it matches [word boundary](https://stackoverflow.com/questions/1324676/what-is-a-word-boundary-in-regex) – Chase Sep 03 '20 at 15:20
  • I believe `[\b]` only [works if the backspace ASCII character already exists in a string](https://stackoverflow.com/a/17438159/8967612). I don't know typescript, so hopefully, someone will help you but it looks like you want to allow/disallow some key-presses, not characters. Moreover, that line you just deleted from the question body is very relevant to what you're trying to do. I would encourage you to rollback the last edit. Relevant information belongs to the post itself, not the comments. – 41686d6564 Sep 03 '20 at 15:21
  • @Chase I thought so too at first but turns out `\b` in a character class (i.e., `[\b]`) does match an ASCII backspace character. See the link in my last comment for more info. – 41686d6564 Sep 03 '20 at 15:24
  • @41686d6564 Apologize, That line seemed redundant as I already explained that exact sentence in my question. – noclist Sep 03 '20 at 15:27
  • You can try its unicode `\u{8}` – Liju Sep 03 '20 at 15:44
  • Try `/^[0-9.\x08]+$/` – Wiktor Stribiżew Sep 03 '20 at 17:40
  • @WiktorStribiżew Thanks, unfortunately `/^[0-9.\x08]+$/.test("Backspace")` isn't returning true – noclist Sep 03 '20 at 18:07
  • `/^[0-9.\x08]+$/.test("\b")` returns `true` – Wiktor Stribiżew Sep 03 '20 at 19:44

1 Answers1

-1

Just add it to your character set, no?

const test = /^[0-9\.\b]+$/.test("1.6\u0008")

console.log(test)
Rubydesic
  • 2,660
  • 7
  • 20