26
\$\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

asked Jan 5, 2016 at 10:15
\$\endgroup\$

2 Answers 2

38
\$\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);
answered Jan 5, 2016 at 10:42
\$\endgroup\$
4
  • 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\$ Commented Jan 5, 2016 at 16:07
  • 4
    \$\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\$ Commented Jan 5, 2016 at 17:06
  • \$\begingroup\$ To handle negative numbers (e.g. s = 'translate(57px, -113px)'): var numbers = s.match(/-?\d+/g).map(Number); \$\endgroup\$ Commented Jan 15, 2018 at 10:20
  • \$\begingroup\$ This method omits the presiding / leading zeros, example "order id # 00123" will result in extracting 123 but not 00123 \$\endgroup\$ Commented Jun 5, 2019 at 14:15
13
\$\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.

answered Jan 15, 2018 at 10:48
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.