简体   繁体   中英

Replace spaces with Regex without replacing empty HTML tags

I wish to replace spaces in something like this:

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

but when I do so using:

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

it messes my css all up and the objects stack on each other like their position is changed to absolute.

How do I replace the spaces without breaking my css or document flow?

Example code:

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

You're turning it into <spanclass='card_costnum'> , which is not valid, and which will break the rest of your HTML. Just reverse the replacements.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM