Skip to content

Instantly share code, notes, and snippets.

@ecarter
Created November 5, 2011 14:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ecarter/1341624 to your computer and use it in GitHub Desktop.
Save ecarter/1341624 to your computer and use it in GitHub Desktop.
encode html in coffeescript
# encode html
escape = (text) ->
replacements =
[/&/g, '&']
[/</g, '&lt;']
[/"/g, '&quot;']
[/'/g, '&#039;']
for r in replacements
text.replace r[0], r[1]
@Yaakov-Belch
Copy link

For three reasons, this doesn't work as written:

  • we need to put brackets around the list: replacements = [ ... ]
  • text.replace doesn't work in-place; we need: text=text.replace r[0], r[1]
  • finally, we need to mention the return value text on an additional line.

The corrected code looks like this:

# encode html
escape = (text) ->
  replacements = [
    [/&/g, '&amp;']
    [/</g, '&lt;']
    [/"/g, '&quot;']
    [/'/g, '&#039;']
  ]
  for r in replacements
    text=text.replace r[0], r[1]
  text

@Yaakov-Belch
Copy link

Here is a shorter version that does the same work:

#encode html
escape = (text) -> 
  txt.replace(/&/g,'&amp;' ).replace(/</g,'&lt;').
      replace(/"/g,'&quot;').replace(/'/g,'&#039;')

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