settingsAccountsettings
Menusettings

Q: Capture the Numbers in JavaScript

+3 votes

Write a JavaScript function that finds all numbers in a sequence of strings.

The input comes as array of strings. Each element represents one of the strings.

Examples:

Input:
The300
What is that?
I think it’s the 3rd movie.
Lets watch it at 22:45

Output:
300 3 22 45


Input:
123a456
789b987
654c321
0

Output:
123 456 789 987 654 321 0


Input:
Let’s go11!!!11!
Okey!1!

Output:
11 11 1


The output is all the numbers, extracted and printed on a single line – each separated by a single space.

asked in JavaScript category by user mitko

2 Answers

+2 votes

My javascript code:

function captNumbers(input) {

    let text = input.join(" ");
    let pattern = /\d+/g;
    let numbers = text.match(pattern);

    console.log(numbers.join(" "));
}

captNumbers([
    "123a456",
    "789b987",
    "654c321",
    "0"
]);
  1. We can use the Array built-in functions and group the input into one string using the Array.join() function
  2. Create the regex pattern: let pattern = /\d+/g;
  3. In case we don’t need capturing subgroups, as it is in this problem, we can just use the String.match() function to get all matches from our string (the regex still has to have the global flag “g”). 

Thus we can write the program in just a few lines….

answered by user eiorgert
+1 vote

my code:

function extractNumbers(arrStr) {

    let pattern = /\d+/g;

    let result = "";

    for (let arrS of arrStr) {

        let match = arrS.match(pattern);

        if (match && match != null) {
            result += match + " ";
        }
    }
    console.log(result.replace(/,/g," "));
}

extractNumbers([
        "123a456",
        "789b987",
        "654c321",
        "0"]
);

//extractNumbers([
//    "The300",
//    "What is that?",
//    "I think it’s the 3rd movie.",
//    "Lets watch it at 22:45"
//]);
answered by user Jolie Ann
...