How to extract and sort numbers from a string containing numbers and text in JavaScript

1 Answer

0 votes
/*
    This program extracts all integer values from a mixed string
    and sorts them using the language's built‑in array sorting mechanism.

    It demonstrates:
      - clear separation of concerns using functions
      - efficient number extraction using regular expressions
      - dynamic storage using arrays
      - fast numeric sorting with sort()
*/

// ------------------------------------------------------------
// Extract all integer values from a mixed string.
// Uses a regular expression to find digit sequences.
// ------------------------------------------------------------
function extractNumbers(text) {
    // Find all sequences of digits in the string
    const matches = text.match(/\d+/g) || [];

    // Convert each match to an integer
    return matches.map(Number);
}

// ------------------------------------------------------------
// Print all numbers in a space‑separated format.
// ------------------------------------------------------------
function printNumbers(numbers) {
    console.log(numbers.join(" "));
}

// ------------------------------------------------------------
// Main 
// ------------------------------------------------------------
function main() {
    const text = "1000withz7 and3 or 99 give42";

    // extract numbers
    const numbers = extractNumbers(text);

    // sort numbers (numeric sort, not lexicographic)
    numbers.sort((a, b) => a - b);

    // display result
    console.log("Sorted numbers:", numbers.join(" "));
}

main();



/*
run:

Sorted numbers: 3 7 42 99 1000

*/

 



answered Aug 12 by avibootz
...