Skip to content

Instantly share code, notes, and snippets.

@alexbihary
Created January 6, 2014 15:54
Show Gist options
  • Save alexbihary/8284842 to your computer and use it in GitHub Desktop.
Save alexbihary/8284842 to your computer and use it in GitHub Desktop.
var safeCharsForCSSContent = /[0-9A-Za-z\`\~\!\@\#\$\%\^\&\*\(\)\-\_\=\+\|\[\{\]\}\:\,<\.\>\/\?]/;
var singleEscapeChars = /[\\\;]/;
function escapeForCSSContent(text) {
var index = 0,
length = text ? text.length : 0,
result = '';
while(index < length) {
var character = text.charAt(index);
if (safeCharsForCSSContent.test(character)) {
result += character;
} else if (singleEscapeChars.test(character)) {
result += '\\' + character;
} else {
var charCode = character.charCodeAt(0),
hexCode = charCode.toString(16).toUpperCase(),
escaped = '\\' + ('0000' + hexCode).slice(-4) + ' ';
result += escaped;
}
index++;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment