given a string such as one of the following:
'2'
'2px'
'2%'
'2em'
'2foobar'
'foobar'
I would like to determine:
1) whether it is a plain number (2 or 2.2), and if it is round it (Math.floor()) and append 'px' to it, so that, '2' or '2.2' becomes '2px'
2) if it's not a plain number determine if it is a valid css value, that is, if it consist of a number (int or float) followed by either 'px', 'em' or '%'. I know there are others but I'll just support those three. If it is, leave it.
3) if not, see if the string begins with a number (int ot float), round it and append 'px'
4) and if not, set it to an empty string
So that the result would be:
'2' -> '2px'
'2.2' -> '2px'
'2%' -> '2%'
'2em' -> '2em'
'2foo' -> '2px'
'foo' -> ''
Is it possible to do this in a compact way (maybe using regex), or by using an existing css validator library for JS?
Here's how with a regex:
var input = '2.7em', output = parseInt(input, 10) + (input.match(/px|%|em/) || 'px')
edit:
var input = '2.7foo'
, number = parseInt(input, 10)
, output = (isNaN(number)) ? '': number + (input.match(/px|%|em/) || 'px');
edit 2: allow for float with em and %:
var inp='3.5em'
, n=parseFloat(inp), p=inp.match(/%|em/)
, output = (isNaN(n)) ? '': (p)?n+p:Math.round(n)+'px';
var input = '2foo';
var output = '';
var tmp;
tmp = parseInt( input.replace(/^[^1-9]*/, '') );
if ( tmp != 'NaN' ) {
if ( tmp + '%' == input ) {
output = tmp + '%';
} else if ( tmp + 'em' == input ) {
output = tmp + 'em';
} else {
output = tmp + 'px';
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With