Get only numbers from string javascript regex

IMO the #3 answer at this time by Chen Dachao is the right way to go if you want to capture any kind of number, but the regular expression can be shortened from:

/[-]{0,1}[\d]*[\.]{0,1}[\d]+/g

to:

/-?\d*\.?\d+/g

For example, this code:

"lin-grad.ient[217deg,rgba[255, 0, 0, -0.8], rgba[-255,0,0,0] 70.71%]".match[/-?\d*\.?\d+/g]

generates this array:

["217","255","0","0","-0.8","-255","0","0","0","70.71"]

I've butchered an MDN linear gradient example so that it fully tests the regexp and doesn't need to scroll here. I think I've included all the possibilities in terms of negative numbers, decimals, unit suffixes like deg and %, inconsistent comma and space usage, and the extra dot/period and hyphen/dash characters within the text "lin-grad.ient". Please let me know if I'm missing something. The only thing I can see that it does not handle is a badly formed decimal number like "0..8".

If you really want an array of numbers, you can convert the entire array in the same line of code:

array = whatever.match[/-?\d*\.?\d+/g].map[Number];

My particular code, which is parsing CSS functions, doesn't need to worry about the non-numeric use of the dot/period character, so the regular expression can be even simpler:

/-?[\d\.]+/g

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    The number from a string in javascript can be extracted into an array of numbers by using the match method. This function takes a regular expression as an argument and extracts the number from the string. Regular expression for extracting a number is [/[\d+]/]. 

    Example 1: This example uses match[] function to extract number from string. 

    html

        

            Extract number from string

        

        

            GeeksforGeeks

            String is "jhkj7682834"

            

                Click the button to extract number

            

            

        

        

            function myGeeks[] {

                var str = "jhkj7682834";

                var matches = str.match[/[\d+]/];

                if [matches] {

                    document.getElementById['GFG'].innerHTML

                            = matches[0];

                }

            }

        

                                   

    Output:

    Example 2: This example uses match[] function to extract number from string. 

    html

        

            Extract number from string

        

        

            GeeksforGeeks

            String is "foo35bar5jhkj88"

            

                The string contains 3 numbers. So the numbers

                are stored in an array and print together

            

            

                Click the button to extract number

            

            

            

        

        

            function myGeeks[] {

                var str = "foo35bar5jhkj88";

                matches = str.match[/\d+/g];

                var i=0

                document.getElementById['GFG'].innerHTML

                    = matches[0] + matches[1] + matches[2];

                document.getElementById["Geeks"].innerHTML

                    = "Where 35 is the first, 5 is the second"

                    + " and 88 is the third number"

        }

        

                       

    Output:

    Example#3 : This example uses reduce method to extract all the number from string.

    HTML

        

            Extract number from string

        

        

            GeeksforGeeks

    String is "jhkj7682834"

            

                Click the button to extract number

            

            

        

        

            function myGeeks[] {

                var str = "jhkj7682834";

                var c = '0123456789'

                function check[x] {

                            return c.includes[x]  ? true : false;

                        }

                var matches = [...str].reduce[[x, y] => check[y] ? x+y : x, '']

                if [matches] {

                    document.getElementById['GFG'].innerHTML

                            = matches;

                }

            }

        

    Output:

    • Before clicking Button:

    reduce [] function

    • After clicking Button:

    reduce[] 

    JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.


    How do I get numbers only from string?

    Try this simple function that will return the numbers from a string:.
    private string GetNumbers[String InputString].
    String Result = "";.
    string Numbers = "0123456789";.
    int i = 0;.
    for [i = 0; i < InputString. Length; i++].
    if[Numbers. Contains[InputString. ElementAt[i]]].

    How can I extract a number from a string in JavaScript?

    The number from a string in javascript can be extracted into an array of numbers by using the match method. This function takes a regular expression as an argument and extracts the number from the string. Regular expression for extracting a number is [/[\d+]/].

    How do you check if a string is a number with RegEx JavaScript?

    Use the RegExp. test[] method to check if a string contains at least one number, e.g. /\d/. test[str] . The test method will return true if the string contains at least one number, otherwise false will be returned.

    How do I match a number in JavaScript?

    To match all numbers and letters in JavaScript, we use \w which is equivalent to RegEx \[A-za-z0–9_]\ . To skip all numbers and letters we use \W . To match only digits we use \d . To not match digits we use \D .

    Chủ Đề