Skip to content

Instantly share code, notes, and snippets.

@dsamarin
Created June 29, 2011 05:23
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 dsamarin/1053210 to your computer and use it in GitHub Desktop.
Save dsamarin/1053210 to your computer and use it in GitHub Desktop.
Quote JavaScript strings
function(value) {
// First we need to find which quote character to use by comparing the
// number of times each occurs in the string.
var quotes_dbl = (value.match(/"/g) || []).length;
var quotes_sgl = (value.match(/'/g) || []).length;
var quote = quotes_sgl <= quotes_dbl ? "'" : '"';
var quote_code = quote.charCodeAt(0);
// Next, we create a new array of substrings which contain escaped or
// unescaped strings.
var i = 0, code, code2, len = value.length, tojoin = [];
while (len--) {
code = value.charCodeAt(i++);
switch (code) {
case 8: tojoin.push("\\b"); break;
case 9: tojoin.push("\\t"); break;
case 10: tojoin.push("\\n"); break;
case 11: tojoin.push("\\v"); break;
case 12: tojoin.push("\\f"); break;
case 13: tojoin.push("\\r"); break;
case 34: /* double quote */
case 39: /* single quote */
tojoin.push(
(code === quote_code ? '\\' : '') +
String.fromCharCode(code)); break;
case 92: tojoin.push("\\\\"); break;
default:
if ((code < 32) || (code > 0xfffd) ||
(code >= 0x7f && code <= 0x9f) ||
(code >= 0xDC00 && code <= 0xDFFF)) {
tojoin.push("\\u" +
(code <= 0xf ? "000" :
(code <= 0xff ? "00" :
(code <= 0xfff ? "0" : ""))) + code.toString(16).toUpperCase());
} else if (code >= 0xD800 && code <= 0xDBFF) {
if (len < 1) {
tojoin.push("\\u"+code.toString(16).toUpperCase());
} else {
code2 = value.charCodeAt(i++);
if ((code2 < 0xDC00) || (code2 > 0xDFFF)) {
tojoin.push("\\u"+code.toString(16).toUpperCase());
i--;
len++;
} else {
tojoin.push(String.fromCharCode(code, code2));
}
len--;
}
} else {
tojoin.push(String.fromCharCode(code));
}
}
}
return quote+tojoin.join("")+quote;
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment