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
2 Answers 2
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);
-
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– Jaxidian2016年01月05日 16:07:00 +00:00Commented 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\$ndugger– ndugger2016年01月05日 17:06:27 +00:00Commented 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\$Sean– Sean2018年01月15日 10:20:41 +00:00Commented 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\$Clain Dsilva– Clain Dsilva2019年06月05日 14:15:09 +00:00Commented Jun 5, 2019 at 14:15
The code will fail in below cases:
- Negative numbers
- Decimal numbers
- 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
[+-]?
: Optional+
or-
sign before number\d+
: Match one or more numbers(?:\.\d+)?
: Optional decimal point.?:
denotes non-capturing group.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.