Divide a number with possible decimal places

I am trying to break the string from which a number occurs. The problem is that a number can sometimes contain decimal numbers.

I tried this with no luck:

str = "hello there can sometimes be decimals like 1.5 in here"
var parts = str.split(/\d*\.?\d*/);

The intended result is an array with everything before the number in the first position, then the number, then the remaining string.

What am I doing wrong?

+4
source share
2 answers

I do not think that this requires a one-line, but something like this should work.

First, the regular expression must be fixed for use +instead of the *first \d, to make sure that it matches the first part:

/\d+\.?\d*/

, :

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);
+4

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;
}
Hide result
0

Source: https://habr.com/ru/post/1569604/


All Articles