Add js lib function for escaping HTML
This commit is contained in:
parent
b1d4d62533
commit
eaa6b33b8e
21
js/lib/__tests__/escape.test.js
Normal file
21
js/lib/__tests__/escape.test.js
Normal file
@ -0,0 +1,21 @@
|
||||
import escape from '../escape'
|
||||
describe('escape', () => {
|
||||
const htmlEscapes = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
"'": ''',
|
||||
'/': '/',
|
||||
}
|
||||
it('should escape each character', () => {
|
||||
for (let [char, escapedChar] of Object.entries(htmlEscapes)) {
|
||||
expect(escape(char)).toBe(escapedChar)
|
||||
}
|
||||
})
|
||||
it('should escape multiple characters', () => {
|
||||
expect(escape('& and < and > and " and \' and /')).toBe(
|
||||
'& and < and > and " and ' and /'
|
||||
)
|
||||
})
|
||||
})
|
20
js/lib/escape.js
Normal file
20
js/lib/escape.js
Normal file
@ -0,0 +1,20 @@
|
||||
// https://stackoverflow.com/a/6020820
|
||||
|
||||
// List of HTML entities for escaping.
|
||||
const htmlEscapes = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
"'": ''',
|
||||
'/': '/',
|
||||
}
|
||||
|
||||
const htmlEscaper = /[&<>"'\/]/g
|
||||
|
||||
// Escape a string for HTML interpolation.
|
||||
const escape = string => {
|
||||
return ('' + string).replace(htmlEscaper, match => htmlEscapes[match])
|
||||
}
|
||||
|
||||
export default escape
|
Loading…
x
Reference in New Issue
Block a user