function fn(str) { var reg = /^[-]?\d*(\.\d{1,2})?/; return str.match(reg)? str.match(reg)[0] : "" } alert([fn("12345"), fn("123-45"), fn("123.4567"), fn(".12345"), fn("-123.456")]);