javascript passing into a function a string containing whitespace is truncated at first whitespace?

Go To StackoverFlow.com

0

can someone explain to me why you can't pass strings containing whitespace as parameters into javascript functions?

here's my code which shows this issue, just hover over the link and you'll see that only "mario" is shown as the title and not "mario and luigi"

 var href='mario and luigi', subject=$('div').data('subject'), 
 size=$('div').data('reviewid'), 
      src=$('div').data('itemid'), className='mini';

      function formatLink(href, subject, src, size, className){            
                if(size=='mini')
                size='height:25px; width:25px;';
                else if(size=='medium')
                size='height:40px; width:40px;';
                else if(size=='large')
                size='height:125px; width:125px;';
                else if(size=='xlarge')
                size='height:180px; width:260px;';                
            return '<a class="pjax" href='+href+' title='+subject+'><span class='+className+'><span class="image-wrap" style="position:relative; display:inline-block; background:url('+src+') no-repeat center center;'+size+'" ><img style="opacity:0;"></span></span><span title='+subject+'>'+subject+'</span></a>';
        }
var link=formatLink(href, subject, src, size, className);
$('div').html(link);
​
2012-04-04 00:56
by tim peterson


6

title='+subject+' should be title="'+subject+'". You need to quote the attribute, otherwise the markup is invalid.

As a bonus, here's an analog of python's format function which makes things like this much easier:

format = function(str, params) {
    return str.replace(/\{(\w+)\}/g, function($0, $1) { return params[$1] });
}

Usage:

html = format(
    '<a class="pjax" href="{href}" title="{subject}"><span class="{className}"... etc',
    {
        href: "some_link",
        subject: "mario and luigi",
        className: "foobar"
    }
)
2012-04-04 00:59
by georg
awesome, thanks thg435 - tim peterson 2012-04-04 01:30


4

return '<a class="pjax" href='+href+' title='+subject+'><span 

You don't have quotes around href attribute so your HTML ends up being href=mario and luigi. Add quotes to fix it (and do the same thing for the title):

return '<a class="pjax" href="'+href+'" title="'+subject+'"><span 
2012-04-04 01:01
by John Kugelman
hi John, thanks! problem solved - tim peterson 2012-04-04 01:32