2012-07-27 71 views
0

从一个字符串,除去多余的或特殊字符我有一个​​功能,除去多余的或特殊字符:遇到问题在使用javascript

function escapeHtml(unsafe) { 
return unsafe 
    .replace(/\r?\n|\r/g, "") 
    .replace(/(\r\n|\n|\r)/gm," ") 
    .replace(/\s+/g," ") 
    .replace(/&/g, "&") 
    .replace(/</g, "&lt;") 
    .replace(/>/g, "&gt;") 
    .replace(/"/g, "&quot;") 
    .replace(/'/g, "&#039;") 
    .replace(/!/g, ""); 
    } 

虽然我称它和我的这部分代码看起来像:

$(".product_json", data).each(function(){ 
    var thisH = $(this).html(); 
    var myNewString = eval('('+ thisH +')'); 
    var toBeEscaped = myNewString.item_description; 
    var escapedString = escapeHtml(toBeEscaped); 
    myNewString.item_description = escapedString; 
    myNewString = JSON.stringify(myNewString); 
     console.log(myNewString); 
//product_json.push(jQuery.parseJSON(myNewString)); 
}); 

但一些它在控制台怎么说的:SyntaxError: unterminated string literal在这个领域

数据看起来像

VINOVO - Lotti TERRENO Hobbystico - Campestre!!! <br /> 
+0

代码很好,所以这是导致问题的数据。你能提供导致错误的示例数据,或者更好的显示它的jsfiddle吗? – Archer 2012-07-27 16:37:44

+0

哪一行产生该错误? – Trott 2012-07-27 16:46:00

+0

@Trott this one:var myNewString = eval('('+ thisH +')'); – user1433900 2012-07-27 16:47:58

回答

1

你在这一行分配一个值thisH

var thisH = $(this).html(); 

然后通过eval()运行它在这条线(用括号括起):

var myNewString = eval('('+ thisH +')'); 

使用调试器来检查当SyntaxError被触发时,值为thisH。用圆括号括起来的JavaScript有效吗?如果没有,那是你的问题。

+0

这是网址:http ://diventarepartner.unicaimmobili.com/proposte-immobiliari/risultato-ricerca-immobili – user1433900 2012-07-27 16:56:38

+0

在eval和有问题的数据看起来像这样:console.log(thisH):{“item_id”:“4271054”,“foto_principale”:“ {tag_foto principale_value}“,”item_localita“:”“,”item_provincia“:”TO“,”item_tipologia“:”Altro“,”item_mq“:”400“,”item_contratto“:”vendita“,”item_prezzo“ 30000“,”item_locali“:”1“,”item_zona“:”mt 500 dal centro“,”item_strada“:”via“,​​”item_indirizzo“:”“,”item_civico“:”“,”item_logoagenzia“资源/ loghi/medium/102.gif“,”item_description“:”VINOVO - Lotti TERRENO Hobbystico - Campestre !!! A mt。500 dal centro paese,adiacente a zona res ..“} – user1433900 2012-07-27 17:00:31

+0

请看Campestre !!! 它有某种换行符 – user1433900 2012-07-27 17:01:13