Skip to content
This repository was archived by the owner on Sep 10, 2023. It is now read-only.

Commit 5d9de3f

Browse files
author
Wilson Lee
committed
Add HTML escaping and unescaping functions
1 parent 641b6dd commit 5d9de3f

File tree

1 file changed

+58
-2
lines changed

1 file changed

+58
-2
lines changed

src/jquery.tokeninput.js

Lines changed: 58 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,18 @@ var DEFAULT_SETTINGS = {
3333
theme: null,
3434
zindex: 999,
3535
resultsLimit: null,
36-
resultsFormatter: function(item){ return "<li>" + item[this.propertyToSearch]+ "</li>" },
37-
tokenFormatter: function(item) { return "<li><p>" + item[this.propertyToSearch] + "</p></li>" },
36+
37+
enableHTML: true,
38+
39+
resultsFormatter: function(item) {
40+
var string = item[this.propertyToSearch];
41+
return "<li>" + (this.enableHTML ? string : _escapeHTML(string)) + "</li>";
42+
},
43+
44+
tokenFormatter: function(item) {
45+
var string = item[this.propertyToSearch];
46+
return "<li><p>" + (this.enableHTML ? string : _escapeHTML(string)) + "</p></li>";
47+
},
3848

3949
// Tokenization settings
4050
tokenLimit: null,
@@ -98,6 +108,44 @@ var KEY = {
98108
COMMA: 188
99109
};
100110

111+
var HTML_ESCAPES = {
112+
'&': '&amp;',
113+
'<': '&lt;',
114+
'>': '&gt;',
115+
'"': '&quot;',
116+
"'": '&#x27;',
117+
'/': '&#x2F;'
118+
};
119+
120+
var HTML_UNESCAPES = {
121+
'&amp;': '&',
122+
'&lt;': '<',
123+
'&gt;': '>',
124+
'&quot;': '"',
125+
'&#x27;': "'",
126+
'&#x2F;': '/'
127+
};
128+
129+
var HTML_ESCAPE_CHARS = /[&<>"'\/]/g;
130+
131+
var HTML_UNESCAPE_TOKENS = /&amp;|&lt;|&gt;|&quot;|&#x27;|&#x2F;/g;
132+
133+
function coerceToString(val) {
134+
return String((val === null || val === undefined) ? '' : val);
135+
}
136+
137+
function _escapeHTML(text) {
138+
return coerceToString(text).replace(HTML_ESCAPE_CHARS, function(match) {
139+
return HTML_ESCAPES[match];
140+
});
141+
}
142+
143+
function _unescapeHTML(text) {
144+
return coerceToString(text).replace(HTML_UNESCAPE_TOKENS, function(match) {
145+
return HTML_UNESCAPES[match];
146+
});
147+
}
148+
101149
// Additional public (exposed) methods
102150
var methods = {
103151
init: function(url_or_data_or_function, options) {
@@ -444,6 +492,14 @@ $.TokenList = function (input, url_or_data, settings) {
444492
// Private functions
445493
//
446494

495+
function escapeHTML(text) {
496+
return settings.enableHTML ? text : _escapeHTML(text);
497+
}
498+
499+
function unescapeHTML(text) {
500+
return settings.enableHTML ? text : _unescapeHTML(text);
501+
}
502+
447503
// Toggles the widget between enabled and disabled state, or according
448504
// to the [disable] parameter.
449505
function toggleDisabled(disable) {

0 commit comments

Comments
 (0)