admin管理员组

文章数量:1023204

For example, how can I get "1.2" and "kg" for x in the following example? Currently, I get "", "1.", and "kg".

function split()
{
    var data = "1.2kg";
    var x = data.split(/([0-9]*[.])?[0-9]+/);
}

For example, how can I get "1.2" and "kg" for x in the following example? Currently, I get "", "1.", and "kg".

function split()
{
    var data = "1.2kg";
    var x = data.split(/([0-9]*[.])?[0-9]+/);
}
Share Improve this question asked May 16, 2020 at 18:29 Damn VegetablesDamn Vegetables 12.5k16 gold badges95 silver badges174 bronze badges 1
  • Instead of split, would capture groups (non-letters)(letters) do it? – user3456014 Commented May 16, 2020 at 18:32
Add a ment  | 

7 Answers 7

Reset to default 5

This should work:

function split()
{
    var data = "1.2kg";
    var x = data.match(/[\d\.]+|\D+/g);
    console.log(x);
}
split();

You can achive this with parseFloat, if you need float value, there is no need for regex.

var data = "1.2kg"; 
console.log(parseFloat(data)) // 1.2

Something like that:

let [value,unit] = data.match(/^[0-9.]*|[a-z]*$/g)

Obviously it's not an enterprise grade solution. If more then one dot, nonalpha characters, uppercase letters appears in input, the result may vary.

['1.2kg',
 '1.2 kg',
 '10.0.0.2 IP',
 '1 square méter' ].map(
    data => data.match(/^[0-9.]*|[a-z]*$/g)
  )

you need to use match and not split. :-)

var data = "1.2kg";
var m = data.match(/[.0-9]+/);
console.log(m[0])

function split()
{
    var data = "hello world";
    var x = data.split(/\s/);
    document.getElementById('test').innerHTML = x
}
split()
<span id="test"></span>

If you look at this simplified post, you will see it removes the item it is matched on. So I don't think split is what you want. what is the variation on the format? You could use simple regex to remove the number?

function doWork() { 
            var str = "1.2kg"; 
            var matches = str.match(/(\d+)\.{0,1}(\d)/); 
              
            if (matches) { 
                document.getElementById('demo').innerHTML 
                        = matches[0]; 
            } 
        } 
        
        doWork()
<p>String is "1.2kg"</p> 
<span id="demo"></span>

I'm not an expert on this, but I got this to work:

var x = data.split(/([0-9]*[.]*[0-9])/);

Alternative: parseFloat and slice (using findIndex)

const parseAndSplitQuantity = s => `${parseFloat(s)} ${
  s.slice( [...s].findIndex( v => /[^0-9|.]/.test(v) ) ) }`;

["1.2kg", "23.45Mb", "100Pound", "20.34Dollar", "23187.22Miles"]
  .forEach( str => console.log(`${str} => ` + parseAndSplitQuantity(str)) );
.as-console-wrapper { top: 0; max-height: 100% !important; }

For example, how can I get "1.2" and "kg" for x in the following example? Currently, I get "", "1.", and "kg".

function split()
{
    var data = "1.2kg";
    var x = data.split(/([0-9]*[.])?[0-9]+/);
}

For example, how can I get "1.2" and "kg" for x in the following example? Currently, I get "", "1.", and "kg".

function split()
{
    var data = "1.2kg";
    var x = data.split(/([0-9]*[.])?[0-9]+/);
}
Share Improve this question asked May 16, 2020 at 18:29 Damn VegetablesDamn Vegetables 12.5k16 gold badges95 silver badges174 bronze badges 1
  • Instead of split, would capture groups (non-letters)(letters) do it? – user3456014 Commented May 16, 2020 at 18:32
Add a ment  | 

7 Answers 7

Reset to default 5

This should work:

function split()
{
    var data = "1.2kg";
    var x = data.match(/[\d\.]+|\D+/g);
    console.log(x);
}
split();

You can achive this with parseFloat, if you need float value, there is no need for regex.

var data = "1.2kg"; 
console.log(parseFloat(data)) // 1.2

Something like that:

let [value,unit] = data.match(/^[0-9.]*|[a-z]*$/g)

Obviously it's not an enterprise grade solution. If more then one dot, nonalpha characters, uppercase letters appears in input, the result may vary.

['1.2kg',
 '1.2 kg',
 '10.0.0.2 IP',
 '1 square méter' ].map(
    data => data.match(/^[0-9.]*|[a-z]*$/g)
  )

you need to use match and not split. :-)

var data = "1.2kg";
var m = data.match(/[.0-9]+/);
console.log(m[0])

function split()
{
    var data = "hello world";
    var x = data.split(/\s/);
    document.getElementById('test').innerHTML = x
}
split()
<span id="test"></span>

If you look at this simplified post, you will see it removes the item it is matched on. So I don't think split is what you want. what is the variation on the format? You could use simple regex to remove the number?

function doWork() { 
            var str = "1.2kg"; 
            var matches = str.match(/(\d+)\.{0,1}(\d)/); 
              
            if (matches) { 
                document.getElementById('demo').innerHTML 
                        = matches[0]; 
            } 
        } 
        
        doWork()
<p>String is "1.2kg"</p> 
<span id="demo"></span>

I'm not an expert on this, but I got this to work:

var x = data.split(/([0-9]*[.]*[0-9])/);

Alternative: parseFloat and slice (using findIndex)

const parseAndSplitQuantity = s => `${parseFloat(s)} ${
  s.slice( [...s].findIndex( v => /[^0-9|.]/.test(v) ) ) }`;

["1.2kg", "23.45Mb", "100Pound", "20.34Dollar", "23187.22Miles"]
  .forEach( str => console.log(`${str} => ` + parseAndSplitQuantity(str)) );
.as-console-wrapper { top: 0; max-height: 100% !important; }

本文标签: javascriptstring splita number (can be float) and stringStack Overflow