Skip to content

Instantly share code, notes, and snippets.

@heartcode
Last active December 26, 2015 12:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heartcode/7155549 to your computer and use it in GitHub Desktop.
Save heartcode/7155549 to your computer and use it in GitHub Desktop.
Useful set of JavaScript snippets
// Replace extra spaces with single ones and get rid of any spaces at the end and beginning of the string.
// http://stackoverflow.com/questions/6163169/replace-multiple-whitespaces-with-single-whitespace-in-javascript-string - Marku Uttula's answer
var s = " too much trailing space "
s = s.replace(/^(\s*)|(\s*)$/g, '').replace(/\s+/g, ' ');
// Determining the base font size, so that we can use em and rem units in JS
// TODO - make it foolproof and compatible with browsers, which handle `getComputedStyle()`
function getDefaultFontSize() {
var el = document.body.appendChild(document.createElement('p'));
el.innerHTML = 'size matters';
el.style['font-size'] = '1em';
var fontSize = document.defaultView.getComputedStyle(el).fontSize;
document.body.removeChild(el);
return fontSize.substring(0, fontSize.indexOf('px'));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment