Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #940 (closed defect: fixed)

Opened 3 years ago

Last modified 3 years ago

javascript escape needs to escape quotes, and newlines

Reported by: mortonda@dgrmm.net Assigned to: David
Priority: normal Milestone: 1.0
Component: ActionPack Version: 0.11.0
Severity: normal Keywords: javascript escape newlines
Cc:

Description

the escape_javscript method in the javscript helper needs to escape quotes (single and double) and newlines. This can make for some tricky gsub lines... this works for me:

def escape_javascript(javascript)
        javascript.gsub!("\r\n", "\\n")
        javascript.gsub!(/\n|\r/, "\\n")
        javascript.gsub(/["']/) {|m| "\\#{m}"} || javascript
end

Attachments

.2 (0 bytes) - added by anonymous on 06/22/05 14:41:25.
4.txt (6.3 kB) - added by anonymous on 07/16/05 05:16:54.

Change History

03/26/05 00:22:31 changed by mortonda@dgrmm.net

slightly shorter version:

def escape_javascript(javascript)
        javascript.gsub!(/\r\n|\n|\r/, "\\n")
        javascript.gsub(/["']/) {|m| "\\#{m}"}
end

03/26/05 01:50:47 changed by mortonda@dgrmm.net

watch out for nil:

def escape_javascript(javascript)
        javascript ||= ''
        javascript.gsub!(/\r\n|\n|\r/, "\\n")
        javascript.gsub(/["']/) {|m| "\\#{m}"}
end

03/26/05 02:01:11 changed by mortonda@dgrmm.net

an alternate one-liner:

def escape_javascript(javascript)
        (javascript || '').gsub(/\r\n|\n|\r/, "\\n").gsub(/["']/) {|m| "\\#{m}"}
end

03/26/05 14:03:59 changed by david

  • status changed from new to closed.
  • resolution set to fixed.

06/22/05 14:41:25 changed by anonymous

  • attachment .2 added.

07/07/05 03:47:52 changed by anonymous

<input type='text' name='strDate' value="07/04/2005" onClick="var calWin = window.open('/Common/Api/Calender/HTMLCalender/1,1007,0-strDate-,00.html?','cal','dependent=yes,width=210,height=260,left=300,top=150,titlebar=yes')" size='10' style='cursor: hand' class=int_input Style=Width:100px; onChange=change(); readonly>&nbsp; <a href='javascript:doNothing()' onClick="var calWin = window.open('/Common/Api/Calender/HTMLCalender/1,1007,0-strDate-,00.html?','cal','dependent=yes,width=210,height=260,left=300,top=150,titlebar=yes')"><img src='/Statics/Calendar/Images/calendar.gif' width='20' height='16' align='top' hspace='0' border='0'></a>

07/16/05 05:16:54 changed by anonymous

  • attachment 4.txt added.

08/12/05 08:05:36 changed by anonymous

gsssddfgdfgsdfgdfg

10/17/05 05:16:47 changed by anonymous

hlkjljn mn