-
Notifications
You must be signed in to change notification settings - Fork 0
/
text2jsvar.js
62 lines (60 loc) · 1.93 KB
/
text2jsvar.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
module.exports = {
convert: (source, double = false) => {
return JSON.stringify(double ? JSON.stringify(source).slice(1, -1).replace(/'/g, '\\\'') : source).slice(1, -1).replace(/'/g, '\\\'');
},
revert: (convertedText, double = false) => {
let output = convertedText;
if (double) {
output = output.replace(/\\\'/g, '\'')
.replace(/\\"/g, '"')
.replace(/\\\\/g, '\\');
}
output = revertEscapeChars(output, 'n');
output = revertEscapeChars(output, 'r');
output = revertEscapeChars(output, 't');
output = revertEscapeChars(output, 'f');
output = output.replace(/\\"/g, '"')
.replace(/\\\'/g, '\'')
.replace(/\\\\/g, '\\');
return output;
}
};
if (!String.prototype.endsWith) {
String.prototype.endsWith = (searchString, position) => {
let subjectString = this.toString();
if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
position = subjectString.length;
}
position -= searchString.length;
let lastIndex = subjectString.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
}
function revertEscapeChars(str, target) {
let spliter = '\\' + target;
let escaper;
switch (target) {
case 'n':
escaper = '\n';
break;
case 'r':
escaper = '\r';
break;
case 't':
escaper = '\t';
break;
default:
escaper = '';
}
let arr = str.split(spliter);
let output = '';
arr.forEach((item, index) => {
output += item;
if (item.endsWith('\\')) {
output += spliter;
} else if (index < arr.length - 1) {
output += escaper;
}
});
return output;
}