最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

JavaScript, string split, a number (can be float) and string - Stack Overflow

matteradmin5PV0评论

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; }

Post a comment

comment list (0)

  1. No comments so far