Created
January 13, 2015 08:33
-
-
Save xieranmaya/eb9e0cd7230eb5218354 to your computer and use it in GitHub Desktop.
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
var escapeJSON = (function() { | |
var _escape = function(string) { | |
string = string == null ? '' : '' + string; | |
return /(?:&|<|>|"|'|`)/.test(string) ? string.replace(/(?:&|<|>|"|'|`)/g, function(match) { | |
var escapeMap = { | |
'&': '&', | |
'<': '<', | |
'>': '>', | |
'"': '"', | |
"'": ''', | |
'`': '`' | |
}; | |
return escapeMap[match]; | |
}) : string; | |
}; | |
var escapeJSON = function escapeJSON(json) { | |
var i, key; | |
if (Object.prototype.toString.call(json) == '[object Array]') { | |
for (i = 0; i < json.length; i++) { | |
json[i] = escapeJSON(json[i]); | |
} | |
return json; | |
} else if (Object.prototype.toString.call(json) == '[object Object]') { | |
for (key in json) { | |
if (json.hasOwnProperty(key)) { | |
json[key] = escapeJSON(json[key]) | |
} | |
} | |
return json | |
} else if (typeof json == 'string') { | |
return _escape(json) | |
} else { | |
return json | |
} | |
}; | |
return escapeJSON; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment