19
\$\begingroup\$

Consider the following string in javascript:

var string="border-radius:90px 20px 30px 40px";

I want to extract the 4 numbers from that string and store them in an array called numbers.To do that I developed the following code:

var numbers=string.split("border-radius:");
numbers=numbers[1].split("px");

This code is working fine but I was wondering if there is a better approach/solution.Any ideas are welcomed

\$\endgroup\$
30
\$\begingroup\$

I used the following regexp to extract numbers from a string:

var string = "border-radius:10px 20px 30px 40px";
var numbers = string.match(/\d+/g).map(Number);
\$\endgroup\$
  • 1
    \$\begingroup\$ This is a much better & more robust solution. I'm sure others can help you make your regex better (not my strength so I'm not commenting on that aspect). \$\endgroup\$ – Jaxidian Jan 5 '16 at 16:07
  • 3
    \$\begingroup\$ If you then want the numbers to be actual numbers instead of strings, you can then map it; the simplest version of this would be: string.match(/\d+/g).map(Number) \$\endgroup\$ – ndugger Jan 5 '16 at 17:06
  • \$\begingroup\$ To handle negative numbers (e.g. s = 'translate(57px, -113px)'): var numbers = s.match(/-?\d+/g).map(Number); \$\endgroup\$ – Sean Jan 15 '18 at 10:20
  • \$\begingroup\$ This method omits the presiding / leading zeros, example "order id # 00123" will result in extracting 123 but not 00123 \$\endgroup\$ – Clain Dsilva Jun 5 '19 at 14:15
10
\$\begingroup\$

The code will fail in below cases:

  1. Negative numbers
  2. Decimal numbers
  3. Units other than px(e.g. pt, %, vw, vh, ...)

Moreover, the numbers array contains space before numbers and an empty string at the end which is not required.


I recommend to use below regex to extract numbers from strings

/[+-]?\d+(?:\.\d+)?/g
  1. [+-]?: Optional + or - sign before number
  2. \d+: Match one or more numbers
  3. (?:\.\d+)?: Optional decimal point. ?: denotes non-capturing group.
  4. g flag: To get all matches

After the numbers are extracted from string, they can be converted to Number format.

var regex = /[+-]?\d+(?:\.\d+)?/g;

var str = `padding: 0;
font-size: 16pt;
width: 50%;
height: 20vh;
margin-right: 12px;
padding-right: -12.5px;`;

var match;
while (match = regex.exec(str)) {
  console.log(match[0]);
}

Here's online demo of the regex on Regex101.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.