Skip to content

Instantly share code, notes, and snippets.

@tristanz
Created September 6, 2014 22:53
Show Gist options
  • Save tristanz/b02ad69cacf768453e47 to your computer and use it in GitHub Desktop.
Save tristanz/b02ad69cacf768453e47 to your computer and use it in GitHub Desktop.
Handle Backspace and Special Characters in Text
applyRewrites = (txt) =>
txt = txt.replace /\r\n/g, "\n"
sofar = ""
remaining = txt
lineBreaks = []
rewritten = false
while m = /[\b\r\n]/.exec(remaining)
switch m[0]
when "\b"
# Handle backspaces. Add everything up to the backspace, then pop off the last character.
sofar += remaining.slice(0, m.index)
if sofar.length > 0
rewritten = true
if sofar[sofar.length - 1] == "\n"
# If a line break got popped, make a note of it.
lineBreaks.pop()
sofar = sofar.slice(0, sofar.length - 1)
when "\n"
# Handle regular newlines. Add everything up to the newline, plus the newline, and
# make a note that we found a newline.
sofar += remaining.slice(0, m.index + 1)
lineBreaks.push sofar.length - 1
when "\r"
# Handle carriage returns. Nuke everything back to the beginning of the current line,
# and drop the newline.
if sofar.length > 0
rewritten = true
if lineBreaks.length > 0
sofar = sofar.slice(0, lineBreaks[lineBreaks.length])
else
sofar = ""
remaining = remaining.slice(m.index + 1)
sofar + remaining
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment