home   articles   tags   browse code   

How to properly escape inline javascript


 

There are 3 ways to include javascript in your webpages.

1. as an external file
<script language='JavaScript' type='text/JavaScript' src='externalfile.js'></script>

2. in the body of your html file
<script language='JavaScript' type='text/JavaScript'>
alert('code for monkeys');
</script>

3. inline in html
<input type="button" value="push me" onclick="alert('code for monkeys');">


Question: How do you call alert when it has singled or double quotes in it?
Well in methods 1 and 2 you simply use ', or " example:
alert('john\'s code');
alert("john's \"code\"");


But what if you want to use inline javascript in html (method 3)? A quick googling of escape quotes in html yields an answer. Use &#34; for " (double quote) and &#39; for ' (single quote).

<input type="button" value="push me1" onclick="alert(&#39;john\&#39;s code&#39;);">
<input type="button" value="push me2" onclick="alert(&#39;john\&#39;s \&#34;code\&#34;&#39;);">

demo:



Now if we are using PHP to generate our html... it gets even worse trying to escape quotes for php, html and javascript and have everything work out correctly.

Use the tag_create() function below to avoid having to code &#39; and &#34;s everywhere.
function tag_create($name,$attributes=array(),$children='')
{    
    if (strlen($children)==0)
        return substr(tag_open($name,$attributes),0,-1)." />";//valid xhtml
    else
        return tag_open($name,$attributes).$children.tag_close($name);
}

function tag_open($name,$attributes=array())
{
    $h="$name ";
    foreach($attributes as $a_name=>$a_value)
    {
        $r = array('\'','"');//replace
        $w=array('&#39;','&#34;');//replacewith
        $h.= strtolower($a_name). "='".str_replace($r, $w, $a_value ) ."' ";
    }
    return "<".substr($h,0,-1).">";//-1 gets rid of last space
}
function tag_close($name)
{
   return "</".$name.">";
}

usage:
$attributes = array();  
$attributes['type']='button';  
$attributes['onclick']="alert(\"john's code for monkeys\");";
echo tag_create('input', $attributes);

This produces the correct output. It doesn't remove the need for all the escaping, but at least if you escape the php string correctly, the code will automatically take care of the &#39; and &#34;s.

 

 


 

 



Related Articles
 




home  |  privacy policy  |  terms of use  |  contact  


©2010, Zedwood Digital