Tag Archives: .js

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

Nifty.

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

Internet Explorer (IE) and the Cached .js File CodeUnit 13 JAN 2011

Internet Explorer and pretty much all other modern web browsers make use of silent caching in order to streamline user experience. Of course, caching is a marvellous tool when needed, but also a frustrating one when you don’t want it turned on. Enter the humble .js javascript include file.

Now IE likes to cache javascript .js file includes, but unfortunately unlike normal web pages, getting it to refresh its cached copy can sometime prove to be quite difficult to achieve.

So here is the solution then.

Simply add a GET variable to the declaration.

If you never want the file to be cached, attach a randomly generated GET variable to the .js declaration for each page load. If you want to control when it gets refreshed, add a GET variable that you change only when you make actual changes to the .js file itself.

Essentially what happens is that IE recognises the URL as a single string, meaning that if the GET variable has changed, the string’s identity has changed, meaning a brand new URL and thus something it will need to go and collect from the internet.

So how does one’s .js file include look now?

<script type=”text/javascript” src=”myscript.js?ver=1″></script>

Simple, but very effective and well worth jotting down.

Nifty.