将\ n替换为JSON字符串中的<br/>

时间:2016-10-03 18:11:53

标签: javascript jquery html json user-interface

我有一个函数来抓取文本数据作为JSON,然后进行字符串化。 我试图在我的网络应用程序中以模态显示此数据,但字符串出现在HTML中,如下所示:

  

{&#34; body&#34;:&#34; --- \ nbl_playout_user:BLplayout \ n \ n#Playout config   值\ nbl_playout_image_drive_mount:   &#39; \\狗仔队\图片&#39; \ nbl_playout_image_path:   &#39; I:&#39; \ nbl_playout_machine_role:Primary \ nbl_playout_network_name:   ABC1 \ nbl_playout_stand_alone_mode:0 \ nbl_playout_run_mode:   HD \ nbl_playout_format:AJA \ nbl_playout_resolution:   720P \ nbl_playout_logo_override:ABC \ nbl_playout_default_header:   BottomLine \ nbl_playout_sponsor_on:15000 \ nbl_playout_sponsor_off:   60000 \ nbl_playout_media_ball_on:15000 \ nbl_playout_media_ball_off:   15000 \ nbl_playout_page_engine_working_directory:&#39; {{   bl_templates_root_dir   } \ SC14_Templates&#39; \ nbl_playout_schema_file_path:&#39; {{   bl_templates_root_dir   } \ SC14_Templates \ BLMaster.xsd&#39; \ nbl_playout_default_swatch_path:&#39; {{   bl_templates_root_dir   }} \ SC14_Templates \ 003_BtmLn_deliverable_ele \ still_ele \ RDBL_GENERIC_SWATCH.png&#39; \ nbl_playout_default_logo_path:   &#39; {{bl_templates_root_dir   }} \ SC14_Templates \ 003_BtmLn_deliverable_ele \ still_ele \ default_team_logo.png&#39; \ n&#34;}

我希望将\n的实例替换为<br>,以便它在HTML中正确显示,但我的功能似乎并没有做到这一点。任何想法为什么?我很难过。

var stringData = JSON.stringify(data);
stringData = stringData.replace(new RegExp('\r?\n','g'), '<br />');
return stringData;

2 个答案:

答案 0 :(得分:6)

试试这个。

stringData = stringData.replace(new RegExp("\\\\n", "g"), "<br />");

或者

stringData = stringData.replace(/\\n/g, "<br />");

答案 1 :(得分:1)

基于评论并建立其他答案..

var json = JSON.parse(stringData);
json.body = body = json.body.replace(/\n/g, "<br />");

// and then if you needed it in a string you can do this again
stringData = JSON.stringify(json);