Search code examples
javascriptsubstringsubstr

Extracting numbers using substring


I have a document where I would like to extract specific numbers from a large list.

I can't list the whole code here, and for the sake of simplicity I will show an example, as the code is not necessary.

for example, say I have a list which appears as below:

1: text,
2: more text,
3: etc

it would be easy to use substring to capture only the first letter in the string, which would be the number I am after. however, what happens when it gets to 10, or 100? keep in mind that I can't change the format or content of the list at all, I can only receive the values in it.

is there a way to get just the number, without the string?


Solution

  • use a regex.

    something like

    var matches = "121: test".match(/^(\d*):\s/)
    var val;
    
    if (matches && matches.length > 0) val = matches[1]
    

    This regex has a bunch of things you might or might not need

    ^ means the beginning of the line
    () means capture this group
    \d* means as many digits as you find in a row
    : is the colon you have in your example
    \s is the single whitespace character after the colon, in your example

    Since we define (\d*), the match method will capture that part of the match (the digits) and make it available in the array.