Skip to content

Instantly share code, notes, and snippets.

@zbinlin
Created February 1, 2015 08:39
Show Gist options
  • Save zbinlin/2bb3f673aba49809042b to your computer and use it in GitHub Desktop.
Save zbinlin/2bb3f673aba49809042b to your computer and use it in GitHub Desktop.
quoteString
/**
* quote function
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/quote|MDN}
* @param {string} str
* @param {string} quote
* @returns {string} quote a string
*/
function quoteString(str, quote) {
str = "" + str;
quote = "" + (quote || "\"");
var meta = {
"\b": "\\b",
"\t": "\\t",
"\n": "\\n",
"\v": "\\v",
"\f": "\\f",
"\r": "\\r",
"\\": "\\\\"
};
meta[quote] = "\\" + quote;
var hexDigits = "0123456789ABCDEF".split("");
var newStr = "";
newStr += quote;
var i, len, ch, cc;
for (i = 0, len = str.length; i < len; i++) {
ch = str[i];
if (meta.hasOwnProperty(ch)) {
newStr += meta[ch];
continue;
}
cc = ch.charCodeAt(0);
if (cc >> 8) {
newStr += "\\u" + hexDigits[(cc >> 12) & 0xF] + hexDigits[(cc >> 8) & 0xF] + hexDigits[(cc >> 4) & 0xF] + hexDigits[cc & 0xF]; // or "\\u" + ("0000" + cc.toString(16).toUpperCase()).slice(-4)
} else {
if (cc > 0x1F && cc < 0x7F) {
newStr += ch;
} else {
newStr += "\\x" + hexDigits[(cc >> 4) & 0xF] + hexDigits[cc & 0xF]; // or "\\x" + ("00" + cc.toString(16).toUpperCase()).slice(-2)
}
}
}
newStr += quote;
return newStr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment