How To Remove All Numbers From A String In JavaScript

Remove all Numbers from a String in JavaScript

To remove all numbers from a string in JavaScript, we have tested effectively with three methods using the replace() method, creating the function to remove all numbers on the string, and using a package. Check out the details below to get more information.

Remove all numbers from a string in JavaScript

Using the replace() method

An easy way to remove all numbers from a string is by using the replace method with a regular expression. It is a very comma way and useful for a developer. We have already explained the replace() method in our other article here. Please read it if you want to get more information.

Code Example

In this example, we can use the replace method to replace all numbers in the string with a space character.

const myString = "Learn1Share2IT33"
console.log("My string is: ", myString)

// Calling replace method with a regular expression to remove all numbers in the string
const newString = myString.replace(/[0-9]/g, '')

console.log("After removing all number in myString: ", newString)

Output

My string is: Learn1Share2IT33
After removing all numbers in myString: LearnShareIT

Creating the function to remove all numbers on the string

Another simple way is creating the function by using the match() method and join() methods in JavaScript. We will match all numbers on a string and join them with the space character.

Example:

const myString = "Learn1Share2IT33"
console.log("My string is: ", myString)

// Creating function remove all number in string with match() and join() methods
function removeNumber(str) {
	return str.match(/\D/g).join('')
}

console.log("After removing all numbers in myString: ", removeNumber(myString))

Output

My string is:
Learn1Share2IT33
After removing all numbers in myString:
LearnShareIT

Using a Package

The last way we want to introduce to you to remove all numbers on the string is by using a @supercharge/strings package. This package is already build-in JavaScript.

Example:

const exStr = require('@supercharge/strings')
const myString = "Learn1Share2IT33"
console.log("My string is: ", myString)
 
// Stripping numbers from a string are already build-in the @supercharge/strings package
const withoutNumbers = exStr(myString).stripNums().get()

console.log("After removing all numbers in myString: ", withoutNumbers)

Output

My string is: Learn1Share2IT33
After removing all numbers in myString: LearnShareIT

Summary

In this tutorial, we have explained how to remove all numbers from a string in JavaScript using many different ways, but we found that using the replace() method is the simplest and most effective. We always hope this tutorial is helpful to you. Leave your comment here if you have any questions or comments to improve the article. Thanks for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *