用Regex替换空格而不替换空HTML标记

时间:2012-04-22 16:57:47

标签: javascript html css

我希望用以下内容替换空格:

<span>5</span>SPACE<image href="mtgsymbol.png" />

但是当我这样做时使用:

card_cost=card_cost.replace(/\s/g,"");

它使我的css全部混乱,并且物体彼此叠加,就像它们的位置变为绝对一样。

如何在不破坏css或文档流的情况下替换空格?

示例代码:

使用Javascript:

card_cost=document.getElementById('card_cost').value;

if(card_cost)
{
card_cost=card_cost.replace(/\d+/g,"<span class='card_costnum'>$&</span>");
*breaks styling*card_cost=card_cost.replace(/\s/g,"");*breaks styling*
}

document.getElementById('output').innerHTML+="<div class='card'>"+"<span class='card_cost'>"+card_cost+"</span>";

CSS:

.card_name,.card_image,.card_cost,.card_type,.card_subtype,.card_rarity,.card_rules,.card_flavor,.card_strength,.card_num,.card_lower,.card_costnum
{
position:relative;
z-index:1;
}

.card_cost
{
display:inline-block;
float:right;
clear:right;
}

.card_costnum
{
position:relative;
display:inline-block;
text-align:center;
vertical-align:middle;
background-image:url("numsymbol_small.png");
background-repeat:no-repeat;
width:12px;
height:12px;
margin:1px;
top:-4px;
}

1 个答案:

答案 0 :(得分:3)

card_cost = card_cost.replace(/\d+/g, "<span class='card_costnum'>$&</span>");
card_cost = card_cost.replace(/\s/g, "");

您将其转换为<spanclass='card_costnum'>,这是无效的,并且会破坏HTML的其余部分。只需撤消替换。

card_cost = card_cost.replace(/\s/g, "");
card_cost = card_cost.replace(/\d+/g, "<span class='card_costnum'>$&</span>");