-
Notifications
You must be signed in to change notification settings - Fork 2
/
str-escape.js
42 lines (40 loc) · 1.26 KB
/
str-escape.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// A simple string escape function.
define(function() { return function str_escape(s) {
if (s.toSource) {
// If available, abuse `toSource()` to properly quote a string
// value.
return s.toSource().slice(12,-2);
}
// Erg, use hand-coded version.
var quotes = '"';
if (s.indexOf('"') !== -1 && s.indexOf("'") === -1) {
quotes = "'";
}
var table = {};
table["\n"] = "n";
table["\r"] = "r";
table["\f"] = "f";
table["\b"] = "b";
table["\t"] = "t";
table["\\"] = "\\";
table[quotes] = quotes;
var result = "", i=0;
while (i < s.length) {
var c = s.charAt(i);
if (table.hasOwnProperty(c)) {
result += "\\" + table[c];
} else if (c < ' ' || c > '~') {
// XXX allow some accented UTF-8 characters (printable ones)?
var cc = c.charCodeAt(0).toString(16);
while (cc.length < 4) {
cc = "0" + cc;
}
result += "\\u" + cc;
} else {
result += c;
}
i += 1;
}
return quotes + result + quotes;
};
});