Last active
December 26, 2015 12:59
-
-
Save heartcode/7155549 to your computer and use it in GitHub Desktop.
Useful set of JavaScript snippets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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