Skip to content

Commit

Permalink
fix: support backslashes
Browse files Browse the repository at this point in the history
  • Loading branch information
erikn69 committed Oct 16, 2023
1 parent fc002f9 commit 204a537
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 3 deletions.
6 changes: 5 additions & 1 deletion lib/escapeHtml.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,11 @@ const charCodeMap = {
38: '&', // &
39: ''', // '
60: '&lt;', // <
62: '&gt;' // >
62: '&gt;', // >
92: '&#92;', // \\
9: '&#92;t', // \t
10: '&#92;n', // \n
13: '&#92;r' // \r
}

function escapeHtml (str) {
Expand Down
3 changes: 3 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,9 @@ function highlight (sqlString, options) {
const escapedContent = options.htmlEscaper(content)
return `<span class="${options.classPrefix}${name}">${escapedContent}</span>`
}
if (name === 'string') {
content = JSON.stringify(content).slice(1, -1).replaceAll('\\"', '"')
}
return options.colors[name] + content + options.colors.clear
})
.join('')
Expand Down
1 change: 1 addition & 0 deletions test/debug.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ console.log(highlight('SELECT id FROM listings WHERE status = "not available"'))

console.log(highlight('SELECT \'{"json_index":"json_value"}\' AS test;'))
console.log(highlight('SELECT "This is a \\"text\\" test" AS text;'))
console.log(highlight('SELECT \'\\\r\t\n\' AS text;'))

console.log(highlight('DROP PROCEDURE IF EXISTS `some-database`.`some-table`;'))

Expand Down
14 changes: 12 additions & 2 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,12 @@ describe('unicode', () => {

it('strings (scaping quotes)', () => {
expect(hlUni('\'\\\'\' "\\"" `\\``'))
.toBe('[string]\'\\\'\'[clear] [string]"\\""[clear] [string]`\\``[clear]')
.toBe('[string]\'\\\\\'\'[clear] [string]"\\\\""[clear] [string]`\\\\``[clear]')
})

it('strings (line breaks)', () => {
expect(hlUni('\'\\\r\n\t\''))
.toBe('[string]\'\\\\\\r\\n\\t\'[clear]')
})

it('integers', () => {
Expand Down Expand Up @@ -155,7 +160,12 @@ describe('html', () => {

it('strings (scaping quotes)', () => {
expect(hlHtml('\'\\\'\' "\\"" `\\``'))
.toBe('<span class="sql-hl-string">&#39;\\&#39;&#39;</span> <span class="sql-hl-string">&quot;\\&quot;&quot;</span> <span class="sql-hl-string">`\\``</span>')
.toBe('<span class="sql-hl-string">&#39;&#92;&#39;&#39;</span> <span class="sql-hl-string">&quot;&#92;&quot;&quot;</span> <span class="sql-hl-string">`&#92;``</span>')
})

it('strings (line breaks)', () => {
expect(hlHtml('\'\\\r\n\t\''))
.toBe('<span class="sql-hl-string">&#39;&#92;&#92;r&#92;n&#92;t&#39;</span>')
})

it('integers', () => {
Expand Down

0 comments on commit 204a537

Please sign in to comment.