How7o
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Reading: How to Keep Only Numbers in a String with JavaScript
Share
How7oHow7o
Font ResizerAa
  • OS
Search
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Follow US
© 2024–2026 How7o. All rights reserved.
How7o > Free Laravel, PHP, WordPress & Server Tutorials > Web Development > How to Keep Only Numbers in a String with JavaScript
Web Development

How to Keep Only Numbers in a String with JavaScript

how7o
By how7o
Last updated: May 22, 2026
4 Min Read
Keep only the digits in a JavaScript string with regex
SHARE

To keep only the digits in a string with JavaScript, use str.replace(/\D/g, '') — the regex \D matches every non-digit character, and replacing them with the empty string leaves only 0–9. The longhand str.replace(/[^0-9]/g, '') works identically.

Contents
  • The one-liner
  • Explicit longhand
  • Keep digits and the decimal point
  • Keep digits, sign, and decimal point
  • Convert the result to a number
  • Frequently asked questions
  • Related guides
  • References

Last verified: 2026-05-17 in Chrome 124, Firefox 125, Safari 17. Originally published 2022-06-30, rewritten and updated 2026-05-17.

The one-liner

const someID = "ID NO. 94854112";
const digits = someID.replace(/\D/g, '');
// "94854112"

\D matches any single character that isn’t a digit, and the /g flag makes the replacement apply to every match (without g, only the first non-digit would go).

JS keep only digits — \\D regex, decimal+comma variants, parseInt conversion

Explicit longhand

const digits = someID.replace(/[^0-9]/g, '');
// "94854112"

The negated character class [^0-9] means “any character that is not a digit 0–9.” Same result as \D, just more explicit.

Keep digits and the decimal point

const price   = "USD $1,299.95";
const numeric = price.replace(/[^0-9.]/g, '');
// "1299.95"

parseFloat(numeric);   // 1299.95

Keep digits, sign, and decimal point

const balance = "$-1,299.95 (overdrawn)";
const numeric = balance.replace(/[^0-9.\-]/g, '');
// "-1299.95"

parseFloat(numeric);   // -1299.95

Escape the dash inside the character class as \- or place it at the start/end of the class so it’s treated as a literal rather than a range marker.

Convert the result to a number

const digits = "ID NO. 94854112".replace(/\D/g, '');

parseInt(digits, 10);    // 94854112  — always pass the radix
Number(digits);          // 94854112  — fine for digits-only strings
+digits;                 // 94854112  — unary plus, same as Number()

Frequently asked questions

What’s the difference between \D and [^0-9]?

\D is a shorthand character class that matches any character that is not a digit. [^0-9] is the explicit equivalent — a negated character class. In ASCII contexts they’re identical and equally fast; \D is shorter and idiomatic. In some Unicode-aware regex flavors, \D can match non-ASCII non-digits differently, but JavaScript’s default regex engine treats them the same.

How do I keep digits and the decimal point?

Allow them in the character class: str.replace(/[^0-9.]/g, ''). For locale-aware numbers (commas as decimal separators in some regions), include the comma too: /[^0-9.,]/g. Note this can leave multiple dots if the input has them — for strict number parsing, also strip extras with a second pass.

Should I parse the result as a number with parseInt or Number()?

parseInt(str, 10) is the standard for integer-only inputs (always pass the radix). Number(str) works too but returns NaN for empty strings and treats "" as 0 inconsistently across operations. For a value that started as digits-only text, parseInt(str, 10) is the predictable pick.

Does \D match negative signs and decimal points?

Yes — - and . are not digits, so they’re matched by \D and stripped. If you’re parsing prices like "$-12.50" and want -12.50 back, allow the sign and dot: str.replace(/[^0-9.\-]/g, '').

Related guides

  • How to Check if a JavaScript String Is a Valid URL
  • How to Check if a Character Is Unicode in JavaScript
  • How to Format a Number with Decimals in JavaScript

References

MDN String.prototype.replace(): developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace. MDN regex character classes: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class.

TAGGED:JavaScriptregexstrings

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
[mc4wp_form]
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article Keep the first N characters of a JavaScript string with slice How to Keep Only the First N Characters of a String in JavaScript
Next Article Load DataTables data via Ajax How to Load Data in DataTables Using Ajax
Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

FacebookLike
XFollow
PinterestPin
InstagramFollow
Most Popular
Run Laravel queue workers with Supervisor
How to Run Laravel Queue Workers in Production with Supervisor
May 23, 2026
Nginx as a reverse proxy for a Node.js app on Ubuntu
How to Set Up Nginx as a Reverse Proxy for Node.js on Ubuntu
May 23, 2026
Install and configure Redis on Ubuntu for Laravel and WordPress
How to Install and Configure Redis on Ubuntu (for Laravel & WordPress)
May 23, 2026
Harden a fresh Ubuntu VPS with UFW, Fail2Ban, and SSH key auth
How to Harden a Fresh Ubuntu VPS: UFW + Fail2Ban + SSH Key Auth
May 23, 2026
Set up Let's Encrypt SSL with Certbot on Ubuntu
How to Set Up Let’s Encrypt SSL with Certbot on Ubuntu (Apache & Nginx)
May 23, 2026

You Might Also Like

Laravel Eloquent count rows — Post::count query snippet with aggregate bar chart icon
Web Development

How to Count Rows in Laravel Eloquent Efficiently

6 Min Read
Enforce a minimum phone-number length in WooCommerce checkout
Web Development

How to Set a Minimum Length for Phone Numbers in WooCommerce

6 Min Read
Check if GD library is installed in PHP (phpinfo and extension_loaded)
Web Development

How to Check if GD Library Is Installed in PHP (3 Easy Methods)

5 Min Read
Upload files via Ajax with jQuery using FormData
Web Development

How to Upload Files via Ajax with jQuery

4 Min Read
How7o

We provide tips, tricks, and advice for improving websites and doing better search.

Tools

  • Age Calculator
  • Word Counter
  • Image Upscaler
  • Password Generator
  • QR Code Generator
  • See all tools→

Pranks

  • Fake Blue Screen Prank
  • Hacker Typer
  • Fake iMessage Generator
  • Windows XP Crash Prank
  • Windows 11 Update Prank
  • See all prank screens →

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service
  • Sitemap
© 2024–2026 How7o. All rights reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?