HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Extract numbers from a string-Javascript

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
javascriptnumbersextractfromstring

Problem

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

Solution

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.

Code Snippets

/[+-]?\d+(?:\.\d+)?/g

Context

StackExchange Code Review Q#115885, answer score: 13

Revisions (0)

No revisions yet.