Skip to content

Commit 6a1df73

Browse files
committed
complete handling for octal escape
1 parent 806eb12 commit 6a1df73

File tree

1 file changed

+22
-8
lines changed

1 file changed

+22
-8
lines changed

src/services/refactors/convertStringOrTemplateLiteral.ts

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ namespace ts.refactor.convertStringOrTemplateLiteral {
139139

140140
while (begin < nodes.length && isStringLiteral(nodes[begin])) {
141141
const next = nodes[begin] as StringLiteral;
142-
text = text + next.text;
142+
text = text + decodeRawString(next.getText());
143143
begin++;
144144
}
145145

@@ -161,7 +161,7 @@ namespace ts.refactor.convertStringOrTemplateLiteral {
161161

162162
while (i + 1 < nodes.length && isStringLiteral(nodes[i + 1])) {
163163
const next = nodes[i + 1] as StringLiteral;
164-
text = text + next.text;
164+
text = text + decodeRawString(next.getText());
165165
i++;
166166
}
167167

@@ -175,13 +175,27 @@ namespace ts.refactor.convertStringOrTemplateLiteral {
175175
return createTemplateExpression(head, templateSpans);
176176
}
177177

178+
const hexToUnicode = (_match: string, grp: string) => String.fromCharCode(parseInt(grp, 16));
179+
const octalToUnicode = (_match: string, grp: string) => String.fromCharCode(parseInt(grp, 8));
180+
181+
function decodeRawString(content: string) {
182+
const outerQuotes = /"((.|\s)*)"/;
183+
const unicodeEscape = /\\u([\d\w]+)/gi;
184+
const unicodeEscapeWithBraces = /\\u\{([\d\w]+\})/gi;
185+
const hexEscape = /\\x([\d\w]+)/gi;
186+
const octalEscape = /\\([0-7]+)/g;
187+
188+
return content.replace(outerQuotes, (_match, grp) => grp)
189+
.replace(unicodeEscape, hexToUnicode)
190+
.replace(unicodeEscapeWithBraces, hexToUnicode)
191+
.replace(hexEscape, hexToUnicode)
192+
.replace(octalEscape, octalToUnicode);
193+
194+
}
195+
178196
function escapeText(content: string) {
179-
// back-tick
180-
return content.replace("`", "\`")
181-
// placeholder alike beginning
182-
.replace("\${", `$\\{`)
183-
// octal escape
184-
.replace(/\\([0-7]+)/g, (_whole, n) => "\\x" + parseInt(n, 8).toString(16));
197+
return content.replace("`", "\`") // back-tick
198+
.replace("\${", `$\\{`); // placeholder alike beginning
185199
}
186200

187201
}

0 commit comments

Comments
 (0)