The Javascript regex function below extracts a single number from a string (including decimal places and minus sign). If a string with multiple numbers is passed the resultant string will concatenate all these number into a single number string.

The resultant string is validated as a number before it is returned. If the input string contains a positive and one or more subsequent negative numbers the number validation will fail. See more on this under ‘Usage example’.

Returns an empty string if the number validation fails.

Function

Javascript
function extractNumber(inputStr) { let res = inputStr.replace(/[^0-9\.-]+/g, ''); if (isNaN(res)) res = ""; return res; }

Parameters

NameOptional/requiredData typeDescription
inputStrRequiredStringThe string from which numbers are to be extracted.

Usage example

Javascript
console.log(extractNumber("Price: 219.95$")); // result: "219.95" console.log(extractNumber("Discount: -80.05$")); // result: "-80.05" console.log(extractNumber("Price: 300$")); // result: "300" console.log(extractNumber("Price: 219.95$, Discount: -80.05$")); // result: "" //notice that positive numbers will be concatenated! console.log(extractNumber("Price: 300$, Discount: 100$")); // result: "300100"