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

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);
jsFiddle Demo
Readup: .replace() | MDN
EDIT:
Try this for your HTML code:
$('#wppizza-article-tiers-118 span span').each(function(){
var text = $(this).text();
text = text.replace(/\b0\b/g, "-");
$(this).text(text);
});
Regex Explained:
/\b0\b/g
Here,
/ is what your regex pattern is enclosed in.
\b means boundary.
0 is what you actually need to replace.
g means global. The replacement will be done globally.
Various Regex tutorials | Google
EDIT2: Here is the working code snippet for the HTML in your question.
$('.wppizza-article-price span').each(function(){
var text = $(this).text();
text = text.replace(/\b0\b/g, "-");
$(this).text(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>

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

Related

How to find start and end index of DOM text selection?

In jQuery Terminal I want to add an API that will return indices of the selection.
Example HTML I have:
<div class="cmd" style="width: 100%; --cursor-line:1; top: 0px;">
<div class="cmd-wrapper" style="">
<span class="cmd-prompt" style="visibility: visible; margin-left: 0px;">
<span data-text="> ">
<span style="width: 2ch;">> </span>
</span>
</span>
<div role="presentation" aria-hidden="true" class="cmd-end-line">
<span data-text="H">
<span>H</span>
</span>
<span data-text="e">
<span>e</span>
</span>
<span data-text="l">
<span>l</span>
</span>
<span data-text="l">
<span>l</span>
</span>
<span data-text="o">
<span>o</span>
</span>
<span data-text=" ">
<span> </span>
</span>
<span data-text="W">
<span>W</span>
</span>
<span data-text="o">
<span>o</span>
</span>
<span data-text="r">
<span>r</span>
</span>
<span data-text="l">
<span>l</span>
</span>
<span data-text="d">
<span>d</span>
</span>
<span data-text=" ">
<span> </span>
</span>
</div>
<div class="cmd-cursor-line" role="presentation" aria-hidden="true">
<span>
<span data-text="x">
<span>x</span>
</span>
<span data-text="x">
<span>x</span>
</span>
<span data-text="x">
<span>x</span>
</span>
<span data-text="x">
<span>x</span>
</span>
<span data-text="x">
<span>x</span>
</span>
</span>
<span class="cmd-cursor" style="">
<span data-text="" class="end">
<span> <span></span></span>
</span>
</span>
<span></span>
</div>
</div>
<textarea autocapitalize="off" spellcheck="false" tabindex="1" class="cmd-clipboard" data-cmd-prompt="> " style=""></textarea>
</div>
This is copy-paste of the DOM after entering "Hello World\nxxxxx" and formatted and pretty printed using https://jsonformatter.org/html-pretty-print
My question is what should I do to get the selection indices?
For example, I have a command like this:
> He|lo wor|d
I should get [2, 8] and if the selection is outside of the range: example
>|>> Hello| world
where >>> is prompt I should get [0, 5] I don't care about the negative. I should also handle when the whole selection is outside
|>>>| Hello World
it should return [0, 0] or null.
How would to implement something like this? Note: that I only care about window.getSelection API it's 100% support, not need to be silly and support
IE8.
You want something like
var range = window.getSelection().getRangeAt(0);
var start = range.startOffset;
var end = range.endOffset;
Note that this code assumes that range.startContainer === range.endContainer (which it often does). If you want to get the text / the length of the text between the start and the end containers, you need to recursively traverse the DOM between them. There is also an issue where the length of the text in the DOM is not the same as the length of the text in HTML (browsers sometimes add spaces and other HTML elements)
You'd be right if you guessed that I've worked a bunch in Javascript with selections. IMO it's kind of a nightmare. Tim Down has written a very popular package called Rangy which I recommend it a lot. You should check it out and see if it meets the requirements of what you are doing.
I've solved the issue myself:
var selection = window.getSelection();
var start = $(selection.anchorNode);
var end = $(selection.focusNode);
var before = start.closest('.cmd [role="presentation"]').prevUntil('.cmd-prompt');
var count = 0;
if (before.length > 1) {
count = before.find('[data-text]').length;
}
var s = start.closest('.cmd [role="presentation"] [data-text]');
var e = end.closest('.cmd [role="presentation"] [data-text]');
if ((s.length || e.length)) {
start = count + s.index();
end = count + e.index() + 1;
console.log({start, end});
}

Get value of a span inside the div when other span is clicked

Here is the structure that I have:
<div class="div1">
<span class="span1">
<span class="span2">X</span>
<span class="span3">some text</span>
</span>
</div>
Question that I have when I click on the span2, is how to pick up via alert for example text of span3?
jQuery
$('.span2').on('click', function() {
var $span3 = $(this).closest('.span1').find('.span3');
console.log($span3.text());
});
Check Fiddle
Vanilla JS
let span2 = document.querySelectorAll('.span2');
Array.from(span2).forEach(function(elem) {
elem.addEventListener('click', function() {
let span3 = this.parentNode.querySelector('.span3');
console.log(span3.innerHTML);
});
});
Check Fiddle
You would need to target the closest parent which is span1 here that contains span3 and then get the text of that element.
Since you're using jQuery you've several choices so you could use .parents() or .siblings() or .next() or also closest() (as shown in Sushanth's answer), to target the related .span3 span :
$('.span2').on('click', function(){
$(this).parents('.span1').find('.span3').text();
//Or
$(this).siblings('.span3').text();
//Or
$(this).next('.span3').text();
})
Hope this helps.
$('.span2').on('click', function(){
console.log( $(this).parents('.span1').find('.span3').text() );
//Or
console.log( $(this).siblings('.span3').text() );
//Or
console.log( $(this).next('.span3').text() );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div1">
<span class="span1">
<span class="span2">X</span>
<span class="span3">some text</span>
</span>
</div>
Edit: Changed it if there are mutliple sets.
Here's a JavaScript example using .nextElementSibling property:
SNIPPET
var d1 = document.querySelector('.div1');
d1.addEventListener('click', function(e) {
var txt = e.target.nextElementSibling.textContent;
alert(txt);
}, false);
.span2 {
border: 1px solid black;
}
.span3 {
pointer-events: none
}
<div class="div1">
<span class="span1">
<span class="span2">X</span>
<span class="span3">some text 1</span>
</span>
<br>
<span class="span1">
<span class="span2">X</span>
<span class="span3">some text 2</span>
</span>
<br>
<span class="span1">
<span class="span2">X</span>
<span class="span3">some text 3</span>
</span>
<br>
<span class="span1">
<span class="span2">X</span>
<span class="span3">some text 4</span>
</span>
</div>

Trim all characters except numbers

Im trying to get the percentage from two numbers. If you loook at the fiddle it works with the first number. For the second numbers I need to trim the first number a bit more, but unsure how.
The first number works.
The second number needs a regex that removes spaces and characters after the numbers.
The third one needs a regex that removes the comma in between numbers , and all characters after the dot.
The fourth one needs a regex that removes the characters before the numbers, the comma between numbers and the dot and all characters behind
How do I write it so it works in all cases? Whatever I try just brakes one or the others.
Fiddle:
https://jsfiddle.net/28dL2fvp/5/
Script:
$('.left').each(function() {
var frstCol = parseInt($(this).find('em.price.product-card-price').text().trim().replace(/[€\.]/g, ''), 10);
var seCol = parseInt($(this).find('em.price.product-card-price.before').text().trim(), 10);
var result = (frstCol / seCol) * 100;
$(this).find('a.pricebubble').text(parseInt(result)|| 0);
});
HTML:
<div class="left">
<em class="price product-card-price">
€1.019 // should count as 1019
<span class="vatstatus">Exclusief BTW</span>
</em>
<em class="price product-card-price before">
1519
</em>
<a class="pricebubble"></a>
</div>
<div class="left">
<em class="price product-card-price">
5 995:- // should count as 5995
<span class="vatstatus">Exclusief BTW</span>
</em>
<em class="price product-card-price before">
987
</em>
<a class="pricebubble"></a>
</div>
<div class="left">
<em class="price product-card-price">
11,823.00SEK // should count as 1183
<span class="vatstatus">Exclusief BTW</span>
</em>
<em class="price product-card-price before">
1987
</em>
<a class="pricebubble"></a>
</div>
<div class="left">
<em class="price product-card-price">
SEK11,823.00 // should count as 1183
<span class="vatstatus">Exclusief BTW</span>
</em>
<em class="price product-card-price before">
1987
</em>
<a class="pricebubble"></a>
</div>
Replacing all but numeric characters
str.replace(new RegExp("[^0-9.]","gm"),"your string");
Suppose you have this string:
var str ="dsfdsf7834hf3876gfergh"
Then, str.replace(new RegExp("[^0-9.]","gm"),"foo");
will return "foofoofoofoofoofoo7834foofoo3876foofoofoofoofoofoo"
Try something like:
str.replace(/[\D]/g, '');
Please try this: (https://jsfiddle.net/28dL2fvp/6/)
$('.left').each(function() {
var frstCol = parseInt($(this).find('em.price.product-card-price').text().replace(/[^0-9.]/g, "").replace(/\.[0-9]*/, ""), 10);
var seCol = parseInt($(this).find('em.price.product-card-price.before').text().replace(/[^0-9.]/g, ""), 10);
var result = (frstCol / seCol) * 100;
console.log("frstCol: ", frstCol, ", seCol: ", seCol);
$(this).find('a.pricebubble').text(parseInt(result)|| 0);
});

Make this regex work with all numbers even though there is no decimals

Im trying to write a script that get the negative percentage number between two numbers. since one number is dynamic and have different currencies, decimals etc I need a regex for that. It almost works, but the first two numbers only work if i add two decimals (.00) to the number. Why is this?
The output on all numbers should be 33.
Fiddle: JSFIDDLE
HTML:
<div class="left">
<em class="price product-card-price">
€1.000
<span class="vatstatus">Exclusief BTW</span>
</em>
<em class="price product-card-price before">
1500
</em>
<a class="pricebubble"></a>
</div>
<div class="left">
<em class="price product-card-price">
1 000:-
<span class="vatstatus">Exclusief BTW</span>
</em>
<em class="price product-card-price before">
1500
</em>
<a class="pricebubble"></a>
</div>
<div class="left">
<em class="price product-card-price">
10,000.00SEK
<span class="vatstatus">Exclusief BTW</span>
</em>
<em class="price product-card-price before">
15000
</em>
<a class="pricebubble"></a>
</div>
<div class="left">
<em class="price product-card-price">
SEK10,000.00
<span class="vatstatus">Exclusief BTW</span>
</em>
<em class="price product-card-price before">
15000
</em>
<a class="pricebubble"></a>
</div>
Script:
$('.left').each(function() {
var frstCol = parseInt($(this).find('em.price.product-card-price').text().replace(/ /g, '').replace(/[^0-9.]|\.(?=\d{3,})/g, "").replace(/(\.\d+)+/,''), 10);
var seCol = parseInt($(this).find('em.price.product-card-price.before').text().replace(/[^0-9.]/g, ""), 10);
var result = 100 - (frstCol / seCol) * 100;
console.log("frstCol: ", frstCol, ", seCol: ", seCol);
$(this).find('a.pricebubble').text(parseInt(result)|| 0);
});
The issue is because both of the em within .left have the same class, so you're picking up the text of both in frstCol. You should use :first to restrict the selector:
var frstCol = parseInt($(this).find('em.price.product-card-price:first').text().replace(/ /g, '').replace(/[^0-9.]|\.(?=\d{3,})/g, "").replace(/(\.\d+)+/,''), 10);
Updated fiddle
Also note that you can simplify your code slightly:
$('.left').each(function() {
var frstCol = parseInt($(this).find('em.price.product-card-price:first').text().trim().replace(/[^0-9.]|\.(?=\d{3,})/g, ""), 10);
var seCol = parseInt($(this).find('em.price.product-card-price.before').text().trim().replace(/[^0-9.]/g, ""), 10);
var result = parseInt(100 - (frstCol / seCol) * 100, 10);
$(this).find('a.pricebubble').text(result || 0);
});

I have 2 price values and I want to calculate the difference

I have 2 price range. Regular Price and Offer Price displayed on screen with the below HTML rendered.
I am trying to calculate the price difference using Javascript/jquery and insert a div with the discount price.
<div class="price-box">
<p class="old-price">
<span class="price-label">Regular Price:</span>
<span class="price" id="old-price-221">Rs17.00 </span>
</p>
<p class="special-price">
<span class="price-label">Special Price</span>
<span class="price" id="product-price-221">Rs14.45 </span>
</p>
<div>
<span>Discount Price:</span>
<span>XXXXXX</span>
</div>
</div>
I have this currency symbol also displayed along with the price. So, I am wondering how to calculate the difference between "Regular Price" and "Special Price".
Can some one please help me?
P.S. I searched the site and did not find the relevant answers.
There it is : http://jsfiddle.net/s7w98ngt/2/
jQuery part :
$('.price-box').each(function(){
var element = $(this),
oldPriceRaw = element.find('.old-price .price').text(),
specialPriceRaw = element.find('.special-price .price').text(),
oldPrice = parseFloat(oldPriceRaw.replace('Rs','')),
specialPrice = parseFloat(specialPriceRaw.replace('Rs','')),
diff = 'Rs'+(oldPrice - specialPrice).toFixed(2), // 2 numbers after the comma
diffElement = element.find('.diff-price');
diffElement.text(diff);
});
HTML a bit modified :
<div class="price-box">
<p class="old-price">
<span class="price-label">Regular Price:</span>
<span class="price" id="old-price-221">Rs17.00 </span>
</p>
<p class="special-price">
<span class="price-label">Special Price</span>
<span class="price" id="product-price-221">Rs14.45 </span>
</p>
<div>
<span>Discount Price:</span>
<span class="diff-price"></span>
</div>
</div>
The tricky thing was to get the current prices value as float numbers. Then, we just calcul the difference.

Categories

Resources