Strip All Non-numeric Characters from String in Javascript

Strip all non-numeric characters from string in JavaScript

When working with JavaScript, you may come across situations where you need to remove all non-numeric characters from a string. This can be useful, for example, when dealing with user input or when manipulating data. In this blog post, we will explore different solutions to achieve this in JavaScript.

Using Regular Expressions

Regular expressions provide a powerful way to match and manipulate strings in JavaScript. We can use a regular expression to match all non-numeric characters and replace them with an empty string.


const str = "abc123def456ghi789";
const strippedStr = str.replace(/D/g, "");
console.log(strippedStr);

This will output:


123456789

In the code snippet above, we use the replace() method with the regular expression /D/g. The D pattern matches any non-digit character, and the g flag ensures that all occurrences are replaced.

Using a Loop and ASCII Values

If you prefer a more traditional approach, you can use a loop to iterate over each character in the string and check if it is a digit. We can achieve this by comparing the ASCII value of each character.


const str = "abc123def456ghi789";
let strippedStr = "";

for (let i = 0; i < str.length; i++) {
  const charCode = str.charCodeAt(i);
  if (charCode >= 48 && charCode <= 57) {
    strippedStr += str[i];
  }
}

console.log(strippedStr);

This will output the same result:


123456789

In the code snippet above, we use the charCodeAt() method to get the ASCII value of each character. We then compare the ASCII value with the range of digits (48-57) and append the character to the strippedStr variable if it is a digit.

Using the isNaN() Function

Another approach is to use the isNaN() function to check if a character is not a number. We can combine this with the filter() and join() methods to remove non-numeric characters.


const str = "abc123def456ghi789";
const strippedStr = Array.from(str).filter(char => !isNaN(char)).join("");
console.log(strippedStr);

This will also output:


123456789

In the code snippet above, we convert the string to an array using Array.from(). We then use the filter() method to remove non-numeric characters by checking if each character is not a number using isNaN(). Finally, we join the filtered array back into a string using join().

These are three different solutions to strip all non-numeric characters from a string in JavaScript. Choose the one that best fits your needs and enjoy manipulating your data with ease!


Posted

in

, ,

by

Tags:

Comments

Leave a Reply

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