In this blog post you learn how to remove the numeric values from a string using JavaScript. Master the art of removing numeric values from strings using various JavaScript techniques. This blog post delves into different ways to achieve this task.
Way 1. With the replace method.
We’ll replace the number present in a string with an empty string with regular expression. Means (“a” to ““).
JavaScript
let string = "Thanks 2 you 4 visiting maketechstuff.com";
let output = string.replace(/[0-9]/g, "");
console.log(string);
// Output:
// Thanks 2 you 4 visiting maketechstuff.com
console.log(output);
// Output:
// Thanks you visiting maketechstuff.com
// Replace the multiple spaces with single space.
console.log(output.trim().replace(/\s+/g, " "));
// Output:
// Thanks you visiting maketechstuff.com
Way 2. Match and Join Method.
The match method returns the matches in a form of array. We make a match method to match non numeric values (/[^0-9]/).
JavaScript
let string = "Thanks 2 you 4 visiting maketechstuff.com";
let match = string.match(/[^0-9]/g);
console.log(string);
// Output:
// Thanks 2 you 4 visiting maketechstuff.com
console.log(match.join(""));
// Output:
// Thanks you visiting maketechstuff.com
Way 3. By combination of split, match methods and for loop.
First we’ll split the string into an array (character array). Then with for loop we match for each array element (character) for number. If it's not a number then we’ll store it in another empty string.
Means we’ll filter out the number from the string with a for loop.
See below code.
JavaScript
let string = "Thanks 2 you 4 visiting maketechstuff.com";
let array = string.split("");
let new_string = "";
for (let i = 0; i < array.length; i++) {
const element = array[i];
if (!element.match(/[0-9]/)) {
new_string += element;
}
}
console.log(string);
// Output:
// Thanks 2 you 4 visiting maketechstuff.com
console.log(new_string);
// Output:
// Thanks you visiting maketechstuff.com
But as you may observe that all the above methods we’ve successfully extracted or removed the number from the string. But there is empty space left of their number, so the space in between words in a string is increased. So we have to replace the multiple spaces with a single space (“good morning” to “good morning”).
We’ll do it by replace methods easily.
Replace many spaces between words to single space.
JavaScript
let string = "Thanks 2 you 4 visiting maketechstuff.com";
let output = string.replace(/[0-9]/g, "");
console.log(string);
// Output:
// Thanks 2 you 4 visiting maketechstuff.com
console.log(output);
// Output:
// Thanks you visiting maketechstuff.com
// Replace the multiple spaces with single space.
console.log(output.trim().replace(/\s+/g, " "));
// Output:
// Thanks you visiting maketechstuff.com
So that's how you can extract the numbers from the string using javascript. If you have any query or suggestion feel free to write in the comment section.
Share your thoughts.