I'm trying to get all numbers inside a string. This can include either whole or rational numbers. I did the hard work of coming up with the regex.
numRegex = /^\d{1,}$|^\d{1,}\.\d{1,}$/
This regex tests if a string is a number.
I have this string
string = "65-KH-ON-PEAK|2.1-K1-ON-PEAK|164-KH-OFF-PEAK|27-K1"
I'm trying to return the following in an array
["65","2.1","1", "164","27", "1"];
If you run the test function on all of those numbers, you will get true returned.
Example
var numbers = ["65", "2.1", "1", "164", "27", "1"];
numbers.every(function(number) {
return numRegex.test(number);
});
=> true
How do I get that output with my regular expression?
You can't use the match
function because that only returns the first instance.
Edit: I tried changing the regex by removing the start
and end
anchors and adding the global
flag. I can't believe I missed that. It does return an array, but it returns too many elements
=> ["65", "2", "1", "1", "164", "27", "1"]