Created
November 8, 2016 13:40
-
-
Save sultaniman/2f5d6bd8829142a3a3f14eeac92a17ea to your computer and use it in GitHub Desktop.
Sanitize HTML inspired by Ember
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const escape = { | |
| '&': '&', | |
| '<': '<', | |
| '>': '>', | |
| '"': '"', | |
| // jscs:disable | |
| "'": ''', | |
| // jscs:enable | |
| '`': '`', | |
| '=': '=' | |
| }; | |
| const possible = /[&<>"'`=]/; | |
| const badChars = /[&<>"'`=]/g; | |
| function escapeChar(chr) { | |
| return escape[chr]; | |
| } | |
| export function escapeExpression(string) { | |
| if (typeof string !== 'string') { | |
| if (string == null) { | |
| return ''; | |
| } else if (!string) { | |
| return string + ''; | |
| } | |
| // Force a string conversion as this will be done by the append regardless and | |
| // the regex test will do this transparently behind the scenes, causing issues if | |
| // an object's to string has escaped characters in it. | |
| string = '' + string; | |
| } | |
| if (possible.test(string)) { | |
| return string.replace(badChars, escapeChar); | |
| } | |
| return string; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment