Remove non-numeric characters from a string using JavaScript

In a situation not involving the DOM, how can you remove all characters except numbers from a string with JavaScript? Characters from 0 to 9 should remain.

let inputString = ‘xyz789.5’;

// the desired result is 7895


How can this be implemented using only JavaScript, ensuring it doesn’t rely on jQuery or browser-specific features?

To achieve the extraction of numbers from a string in JavaScript without involving the DOM or using libraries like jQuery, you can utilize regular expressions. This method focuses purely on JavaScript’s built-in functionalities, ensuring compatibility and simplicity. Here’s how you can do it:

let inputString = 'xyz789.5';

// Use regular expression to replace non-numeric characters with an empty string
let numbersOnly = inputString.replace(/\D/g, ''); // \D matches any non-digit

console.log(numbersOnly); // Output: 7895

Explanation:

  • \D: This is a regular expression pattern that matches any character that is not a digit (0-9).
  • replace(/\D/g, ''): The replace method is used to replace all non-numeric characters with an empty string. The g flag ensures that the replacement happens globally, affecting all occurrences within the string.

This simple solution is efficient and makes sure you get a string with only numbers, without any external dependencies.

To ensure you extract only numbers from a string using JavaScript, a practical approach would be to harness regular expressions, a powerful feature built directly into the language. This solution works universally across environments and does not rely on any libraries or the DOM, ensuring broad compatibility and simplicity.

Here’s a step-by-step example:

Example Code:

let inputString = 'xyz789.5';

// Match all numeric characters in the string
let numericCharacters = inputString.match(/\d+/g);

// Join matched numbers into a single string
let numbersOnly = numericCharacters ? numericCharacters.join('') : '';

console.log(numbersOnly); // Output: 7895

Explanation:

  • \d: This is a regular expression pattern that matches any digit (0-9).
  • /\d+/g: Using this pattern within the match method retrieves all sequences of digits found in the string. The + quantifier ensures that sequences of numbers are matched, not just single digits, and the g flag makes the search global, capturing all such sequences.
  • join(''): The join method is used to concatenate the array of number sequences into a single string, providing a streamlined result.

This method efficiently isolates and collects numeric sequences within a string, making it both effective and easy to understand, catering to various programming skill levels.