Javascript: How to Extract a Number from a String Programming 04 JUL 2013

javascript logoIn my web development work, I’m quite fond of using the trick of generating grouped elements by making sure their IDs all share a common number with a bit of unique text.

So for example I could have a set of elements with the IDs accordionheading1, accordionpanel1, accordiontext1 and accordionheading2, accordionpanel2, accordiontext2. Now in order for this to be useful, I need to be able to extract the number from these strings so that I can automatically guess an element’s associated partners, meaning that you now know exactly what is coming next:

One of the easier ways of extracting a number from a string using javascript is by making use of a bit of regex, utilizing the digit negated shorthand character class \D to do our dirty work.

In practice:

var element = 'accordion24paneldrop';
id = element.replace( /\D+/g, '');
alert(id); //24


Check it else for yourself using JSFiddle! (JS Bin is pretty cool too)

About Craig Lotter

Software developer, husband and dad to two young ladies. Writer behind An Exploring South African. I don't have time for myself any more.