2009/06/24

escape single quote in javascript

Problem:

alias_term = trim(alias_term);
var str = '<a href="javascript:updt_mapping(\'alias\',\''+alias_term+'\');">Update Alias</a>';
Using above code, when the alias_term is something like k’nex, which has single quote, it would broke the javascript, for the javascript statement become updt_mapping(‘alias’, ‘k’net’)

Solution:

escape single quote, but you could not using escape function, alias_term = escape(alias_term), but replace function, alias_term = alias_term.replace(/\'/,"\\'");

No comments:

Post a Comment