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]+/);
}
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)
)
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>
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; }