DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Split Value From Units

04.10.2005
| 8245 views |
  • submit to reddit
        this is a very basic script for seperating out values and units.  this is helpful for changing values such as style.top or border.

if element.style.top => '15px'
splitUnit( element.style.top ) => [15,'px']

function splitUnit(e)
/*
*	takes a string and seperates 'px or 'em' from it
*
*	could be streamlined to simply seperate the last two characters, but that could cause errors if used sloppily
*/
{
	if( e && ( length = e.search( /px/ ) ) ) {var eUnit = 'px'; var eValue = e.substr( 0, length );}
	else if( e && ( length = e.search( /em/ ) ) ) {var eUnit = 'em'; var eValue = e.substr( 0, length );}
	else return false;
	
	return new Array( eValue, eUnit );
}