Skip to content

Instantly share code, notes, and snippets.

@atesgoral
Forked from 140bytes/LICENSE.txt
Created May 24, 2011 17:35
Show Gist options
  • Save atesgoral/989212 to your computer and use it in GitHub Desktop.
Save atesgoral/989212 to your computer and use it in GitHub Desktop.
XML-escape given string
function (s) {
return s.replace(
/[&<>'"]/g, // All characters we want to escape
function (c){
return "&" // prefix
+ { // lookup map
"&": "amp",
"<": "lt",
">": "gt",
"'": "apos",
'"': "quot"
}[c]
+ ";" // suffix
})
}
function(s){return s.replace(/[&<>'"]/g,function(c){return "&"+{"&":"amp","<":"lt",">":"gt","'":"apos",'"':"quot"}[c]+";"})}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Ates Goral <http://magnetiq.com>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "xmlEscape",
"description": "Escape basic XML characters",
"keywords": [
"string",
"escaping",
"xml"
]
}
var xmlEscape = function(s){return s.replace(/[&<>'"]/g,function(c){return "&"+{"&":"amp","<":"lt",">":"gt","'":"apos",'"':"quot"}[c]+";"})};
console.log(xmlEscape("testing <element attribute=\"value\"> & apostrophe (')"));
// testing &lt;element attribute=&quot;value&quot;&gt; &amp; apostrophe (&apos;)
@eligrey
Copy link

eligrey commented Sep 19, 2011

Even shorter:

// 56 bytes
function(s){return new Audio(s).outerHTML.slice(27,-10)}

@atesgoral
Copy link
Author

@eligrey: Wow! Hax!

Same char len (56), a different take:

function(s){return new Audio(s).outerHTML.split('"')[3]}

@mathiasbynens
Copy link

@atesgoral and @eligrey, those last two versions don’t escape single quotes though, so you’d still need .replace(/'/g,'&#37;').

// 78 bytes, but doesn’t work in IE < 9
function(s){return new Audio(s).outerHTML.slice(27,-10).replace(/'/g,'&#37;')}

@atk
Copy link

atk commented Sep 19, 2011

While Option is available even in IE6, Audio is not even present in IE8.

@mathiasbynens
Copy link

@atk

While Option is available even in IE6 […]

It is available in IE6 but it doesn’t work the way it’s being used here.

@jimmywarting
Copy link

I win, 39 byte

s=>new Audio(s).outerHTML.slice(27,-10)

@atesgoral
Copy link
Author

@jimmywarting ES6 FTW!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment