3

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]+/);
}
1
  • Instead of split, would capture groups (non-letters)(letters) do it? Commented May 16, 2020 at 18:32

7 Answers 7

5

This should work:

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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)
  )

2 Comments

It works, but it creates 3 elements, of which the last element is an empty string. I can ignore the last one, but why does it create 3?
match creates always array . Then if you use match rather than replace than you can take first element of array
0

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

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

Comments

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>

Comments

0

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

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.