Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript string regex (css validity check+conversion)

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?

like image 265
mikkelbreum Avatar asked Dec 21 '22 15:12

mikkelbreum


2 Answers

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';
like image 97
herostwist Avatar answered Dec 24 '22 05:12

herostwist


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';
  }
}
like image 38
hsz Avatar answered Dec 24 '22 06:12

hsz