Use a fallback for invalid input
Try reading a whole number from a short piece of text. Here the form uses zero when someone types a word instead of a number.
RegExp.test and Number
Simple example
Read the number in this text.
Start"3"
Result3
const input: string = "3";
const number = /^-?[0-9]+$/.test(input) ? Number(input) : 0;
console.log(number);
3
Advertisements
Everyday examples
A club form expects a number of guests. Someone enters none. How many extra seats does it reserve?
Start"none"
Result0
const input: string = "none";
const number = /^-?[0-9]+$/.test(input) ? Number(input) : 0;
console.log(number);
0
The parcel desk receives the package count as text. Read the count for the loading slip.
Start"12"
Result12
const input: string = "12";
const number = /^-?[0-9]+$/.test(input) ? Number(input) : 0;
console.log(number);
12
A learner enters two dashes for the number of extra notebooks. What default quantity goes on the order?
Start"--"
Result0
const input: string = "--";
const number = /^-?[0-9]+$/.test(input) ? Number(input) : 0;
console.log(number);
0