当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - jQuery: Find specific number & replace with specific string

问题描述:

I am using a food menu in my website.

In my food menu you can select what you want with your meat.

For example:

shawarma: pita:10$ Baguette:12$ Plate: 17$

steak: pita: 20 Baguette:none Plate:35$

the problem is when some of the menu items dont have one of the pita or Baguette or Plate, the script will print zero "0"

steak: pita: 20 Baguette:0 Plate:35$

I am trying to Find all the 0 number and replace with -.

the problem is that in some items the price come with 0 like 10, 20, 30, etc...

here i don't want to change the "0" to "-"

I tried to use this code: (but this code not makes me what i need)

Any suggestions?

 jQuery(document).ready(function($) {

$("div").find(":contains('0')").each(function(){

$this = $(this);

$this.text("-");

});

});

the html looks:

<div id="wppizza-article-tiers-118" class="wppizza-article-tiers">

<span id="wppizza-118-4-0" class="wppizza-article-price ">

<span>0 $</span>

<div class="wppizza-article-price-lbl wppizza-no-cart">Toast</div>

</span>

<span id="wppizza-118-4-1" class="wppizza-article-price ">

<span>20 $</span>

<div class="wppizza-article-price-lbl wppizza-no-cart">Big Pita</div>

</span>

<span id="wppizza-118-4-2" class="wppizza-article-price ">

<span>33 $</span>

<div class="wppizza-article-price-lbl wppizza-no-cart">Baguette</div>

</span>

<span id="wppizza-118-4-3" class="wppizza-article-price ">

<span>35 $</span>

<div class="wppizza-article-price-lbl wppizza-no-cart">לאפה</div>

</span>

<span id="wppizza-118-4-4" class="wppizza-article-price ">

<span>49 $</span>

<div class="wppizza-article-price-lbl wppizza-no-cart">Plate</div>

</span>

</div>

网友答案:

A simple Regular Expression with .replace() will do that: /\b0\b/g

Working Code Snippet:

var myString = "steak: pita: 20 Baguette:0 Plate:35$";

myString = myString.replace("/\b0\b/g", "-");

alert(myString);
网友答案:
 jQuery(document).ready(function() {
    $(".wppizza-article-price").each(function(){
        var value = $(this).find('span').text();
        if (value == '0 $') {
           $(this).find('span').text('-'); 
        }
    });
 });

it will work now DEMO

分享给朋友:
您可能感兴趣的文章:
随机阅读: