簡體   English   中英

用正則表達式替換空格,而不替換空的HTML標簽

[英]Replace spaces with Regex without replacing empty HTML tags

我希望在這樣的地方替換空格:

<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;
}
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>");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM