Reputation: 313
I'm trying to split a string from where a number is encountered. The problem is the number can sometimes have decimals in it.
I tried this without any luck:
str = "hello there can sometimes be decimals like 1.5 in here"
var parts = str.split(/\d*\.?\d*/);
The intended result would be an array with everything before the number in first position, then the number, then the rest of the string.
What am I doing wrong?
Upvotes: 4
Views: 59
Reputation: 446
var str = 'hello there can sometimes be decimals like 1.5 in here';
var firstDigit = str.indexOf(str.match(/\d/))-1 ;
function splitValue(value, index) {
var parts =[value.substring(0, index),value.substring(index)] ;
return parts;
}
Upvotes: 0
Reputation: 33399
I don't think there's a one-liner for this, but something like this should work.
First the regex needs to be fixed to use +
instead of *
by the first \d
, to make sure it matches the first part:
/\d+\.?\d*/
Then, we need to extract the number, split, and add it into the array:
str = "hello there can sometimes be decimals like 1.5 in here"
var num = str.match(/\d+\.?\d*/);
var parts = str.split(/\d+\.?\d*/);
parts.splice(1,0,num);
Upvotes: 4