Estafette
Compose Login
You are browsing eu.zone1 in read-only mode. Log in to participate.
rss-bridge 2024-01-16T11:48:41+00:00

Extract a Number from a String with JavaScript

User input from HTML form fields is generally provided to JavaScript as a string. We’ve lived with that fact for decades but sometimes developers need to extract numbers from that string. There are multiple ways to get those numbers but let’s rely on regular expressions to extract those numbers! To employ a regular expression to […]
The post Extract a Number from a String with JavaScript appeared first on David Walsh Blog.

---

Extract a Number from a String with JavaScript

David Walsh on
January 16, 2024

- 1

User input from HTML form fields is generally provided to JavaScript as a string. We've lived with that fact for decades but sometimes developers need to extract numbers from that string. There are multiple ways to get those numbers but let's rely on regular expressions to extract those numbers!

To employ a regular expression to get a number within a string, we can use \d+:

`
const string = "x12345david";
const [match] = string.match(/(\d+)/);
match; // 12345

`

Regular expressions are capable of really powerful operations within JavaScript; this practice is one of the easier operations. Converting the number using a Number() wrapper will give you the number as a Number type.

-->

[Image: Request Metrics real user monitoring]

[Image: Request Metrics real user monitoring]

---

[Original source](https://davidwalsh.name/javascript-extract-string)

Reply