Skip to content

Instantly share code, notes, and snippets.

@myfonj
Created May 27, 2014 17:46
Show Gist options
  • Save myfonj/975548acd8155ed4fed0 to your computer and use it in GitHub Desktop.
Save myfonj/975548acd8155ed4fed0 to your computer and use it in GitHub Desktop.
Javascript multiline string expression shim
<!DOCTYPE HTML><html><head><meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=7" />
<title>Javascript multiline string expression shim</title><style type="text/css">
body{background-color:#333;color:#ccc;max-width:40em;margin:0 auto;}
h1,h2,h3,em,strong,th,thead,label,dt,legend,caption{color:#fff}
a:link{color:#6ff}a:visited{color:#9f3}label:hover,a:hover{background-color:#000}
html *{font-family:"Courier New",monospace}
pre{tab-size:2;-moz-tab-size:2;background-color: #444}
</style></head><body>
<script type="text/javascript">
var str;
str = (function(f){
return f.toString().replace(/^[^/]+\/\*\s*|\s*\*\/[^/]*$/g,'')
})(function(){
/*
Multiline ----
------- String
no need to \n,
no "e's"c'a"p'ing"
closure with anon func passed to annon func
two functions, hmm…
*/
})
document.write('<pre>»'+str+'«</pre>')
str = (function f(){return f.toString().replace(/^[\s\S]*?\/\*\s*|\s*\*\/[^/]*$/g,'')/*
Multiline ----
------- String
no need to \n,
no "e's"c'a"p'ing"
cosure with single named function expression
shortest, but creates local variable `f` in IE LTE 8
(in other browsers it follows specs and does not polute context)
*/})()
document.write('<pre>»'+str+'«</pre>')
str = (function f(){var s=f.toString();return s.slice(s.indexOf('/'+'*')+3,s.lastIndexOf('*/'))
/*
Multiline ----
------- String
no need to \n,
no "e's"c'a"p'ing"
same as prevoius, no regular expression
(nut not trimmed enclosing linebreaks
*/
})()
document.write('<pre>»'+str+'«</pre>')
str = (function(){return arguments.callee.toString().replace(/^[\s\S]*?\/\*\s*|\s*\*\/[^/]*$/g,'')
/*
Multiline ----
------- String
no need to \n,
no "e's"c'a"p'ing"
closure with single anonymous function using arguments.callee
will not work in "strict mode"
*/
})()
document.write('<pre>»'+str+'«</pre>')
</script>
<p>Limitations:
<ul>
<li>no <code>*/</code> in the string
<li>no varibles or other processing (but think templates or sprintf)
</ul>
</body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment