Skip to content

Commit 1acaaad

Browse files
committed
feat: add escapeHTML function
This can be used to escape any special characters in a string with HTML before sending from the server back to the client. This is important to prevent a cross-site scripting attack.
1 parent d2f0e17 commit 1acaaad

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

src/node/util.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -509,3 +509,17 @@ export const isFile = async (path: string): Promise<boolean> => {
509509
return false
510510
}
511511
}
512+
513+
/**
514+
* Escapes any HTML string special characters, like &, <, >, ", and '.
515+
*
516+
* Source: https://stackoverflow.com/a/6234804/3015595
517+
**/
518+
export function escapeHTML(unsafe: string): string {
519+
return unsafe
520+
.replace(/&/g, "&amp;")
521+
.replace(/</g, "&lt;")
522+
.replace(/>/g, "&gt;")
523+
.replace(/"/g, "&quot;")
524+
.replace(/'/g, "&#039;")
525+
}

test/unit/node/util.test.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -434,3 +434,11 @@ describe("onLine", () => {
434434
expect(await received).toEqual(expected)
435435
})
436436
})
437+
438+
describe("escapeHTML", () => {
439+
it("should escape HTML", () => {
440+
expect(util.escapeHTML(`<div class="error">"Hello & world"</div>`)).toBe(
441+
"&lt;div class=&quot;error&quot;&gt;&quot;Hello &amp; world&quot;&lt;/div&gt;",
442+
)
443+
})
444+
})

0 commit comments

Comments
 (0)