如何使用Javascript删除html标签中不需要的空格?

时间:2013-07-23 13:04:36

标签: javascript jquery html-table trim html-entities

我有一个Javascript变量。变量如下所示

 var str = '< table class = "buy_selection" >
 < tbody > 
 < tr >
 < th > size < / th >
 < td >
 < select id = "Specification_select" name = "Specification" >
 < option value = "014 black / white" > 014 black / white < / option >
 < option value = "100 white/v red" > 100/v red white < / option > 
 < option value = "101 white/black" > 101 white/black < / option > 
 < option value = "102 white/white" > 102/white < / option >
 < / select > 
 < / Td >
 < / tr > 
 < tr >
 < th > color < / th > 
 < td >
 < select id = "Specification_select" name = "Specification" >
 < option value = "23.0" > 23.0 < / option > 
 < option value = "23.5" > 23.5 < / option >
 < option value = "24.0" > 24.0 < / option > 24.5 
 < option value = "24.5" > < / option > 
 < option value = "25.0" > 25.0 < / option >
 < option value = "25.5" > 25.5 < / option >
 < option value = "26.0" > 26.0 < / option > 
 < option value = "26.5" > 26. 5 < / option > 
 < option value = "27.0" > 27.0 < / option > 
 < option value = "27.5" > 27.5 < / option > 
 < option value = "28.0" > 28.0 < / option >
 < option value = "28.5" > 28.5 < / option > 
 < option value = "29.0" > 29.0 < / option > 
 < option value = "30.0" > 30.0 < / option >
 < option value = "30.5" > 30.5 < / option > 
 < option value = "31.0" > 31.0 < / option > 
 < / select > 
 < / td >
 < / tr > write < tr > 
 < th > reviews 10 0 Yen discount < / th >
 < td >
 < select id = "Specification_select" name = "Specification" >,
 < option value = "review to write" > write reviews < / option >
 < option value = "write a review [100-yen discount]" > [100-yen discount] write a review < / option >
 < / select > 
 < / td > 
 < / tr > 
 < / tbody > ';

我需要格式化这个表并使用Javascript或jQuery分配到一个div中。

我已尝试trim()html_entity_decode,但未删除任何不需要的空格。

< table class = "buy_selection" >

我如何格式化变量。请指教。

2 个答案:

答案 0 :(得分:3)

您是否尝试制作它的DOM元素,并将其HTML格式化回来?

var new_table = $("<div>"+str+"</div>"); // create a new DOM DIV containing the element with the given text

str_without_spaces = new_table.html();

但无论如何,你真的需要删除空格吗?我的意思是,当你使用上面的第一行时,它会创建一个DOM表,其中所有空格都消失(因为“&lt;”和“&gt;”之间的空格被删除,如果它们不是html,则删除标签内的空格码)。

最简单的方法是使用$(str);创建DOM元素,并将其附加到html页面中的内容。

答案 1 :(得分:1)

我对此有点不好,但这应该这样做

str = str.replace(/< /g, '<').replace(/<\/ /g, '</').replace(/ >/g, '>').replace(/\/ /g, '/')

FIDDLE