How can I extract a number from a string in JavaScript?

For this specific example, var thenum = thestring.replace( /^\D+/g, ”); // replace all leading non-digits with nothing in the general case: thenum = “foo3bar5”.match(/\d+/)[0] // “3” Since this answer gained popularity for some reason, here’s a bonus: regex generator. function getre(str, num) { if(str === num) return ‘nice try’; var res = [/^\D+/g,/\D+$/g,/^\D+|\D+$/g,/\D+/g,/\D.*/g, /.*\D/g,/^\D+|\D.*$/g,/.*\D(?=\d)|\D+$/g]; for(var … Read more

What’s the best way to convert a number to a string in JavaScript?

like this: var foo = 45; var bar=”” + foo; Actually, even though I typically do it like this for simple convenience, over 1,000s of iterations it appears for raw speed there is an advantage for .toString() See Performance tests here (not by me, but found when I went to write my own): http://jsben.ch/#/ghQYR Fastest … Read more

Can I hide the HTML5 number input’s spin box?

This CSS effectively hides the spin-button for webkit browsers (have tested it in Chrome 7.0.517.44 and Safari Version 5.0.2 (6533.18.5)): input::-webkit-outer-spin-button, input::-webkit-inner-spin-button { /* display: none; <- Crashes Chrome on hover */ -webkit-appearance: none; margin: 0; /* <– Apparently some margin are still there even though it’s hidden */ } input[type=number] { -moz-appearance:textfield; /* Firefox … Read more

How to sort an array of integers correctly

By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) – var numArray = [140000, 104, 99]; numArray.sort(function(a, b) { if( a === Infinity ) return 1; else if( isNaN(a)) return -1; else return a – b; }); console.log(numArray); Documentation: Mozilla Array.prototype.sort() … Read more