patternjavascriptModerate
Extract numbers from a string-Javascript
Viewed 0 times
javascriptnumbersextractfromstring
Problem
Consider the following string in javascript:
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:
This code is working fine but I was wondering if there is a better approach/solution.Any ideas are welcomed
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
Solution
The code will fail in below cases:
Moreover, the
I recommend to use below regex to extract numbers from strings
After the numbers are extracted from string, they can be converted to Number format.
font-size: 16pt;
width: 50%;
height: 20vh;
margin-right: 12px;
padding-right: -12.5px;
Here's online demo of the regex on Regex101.
- 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.
gflag: 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.
Code Snippets
/[+-]?\d+(?:\.\d+)?/gContext
StackExchange Code Review Q#115885, answer score: 13
Revisions (0)
No revisions yet.