Using Javascript to add a span around a decimal value - javascript

var value = 2.00
How can I add a span tag around the '.00', so that on my page I would end up with:
2<span>.00</span>
Please note that the '00' can be a different value. Depends on the data being injected.

You can use String#replace
var value = '2.00';
console.log(
value.replace(/\.(\d+)/, '.<sapn>$1</span>')
);
If variable holds a Number then convert it to 2 decimal format string using Number#toFixed and do the same.
var value = 2.00;
console.log(
value.toFixed(2).replace(/\.(\d+)/, '.<sapn>$1</span>')
);
Refer : Specifying a string as a parameter in replace method.

split it into the two parts and add a span to the second part.not sure if you want the decimal place inside the span or not, but this will do it.
var value = '2.00';
var valueParts=value.split(".");
var newValue=valueParts[0] +"<span>."+valueParts[1]+ "</span>";
alert(newValue);

Use the toFixed function
var num = 5.56789;
var n = num.toFixed(2);
if you need back the string to number you can use parseFloat function
var num = parseFloat(n)

You are specifically asking for a "span tag", so here is a JQuery approach:
$(document).ready(function () {
var value = 2.00
value = value.toFixed(2);
$('body').append(value.split('.')[0] + '<span>.' + value.split('.')[1] + '</span>');
});
See this jsfiddle example: https://jsfiddle.net/fictus/tj7df8qh/

Related

how to replace multiple special character in a number?

I have a number say 2,500.00 and i want to convert the number into 2.500,00. So, we can replace the special character using replace like
var x = 2,500.00;
x.replace(/,/g,".");
and for "Dot" also, we can do it. But in this case, it won't work because when we apply replace function for comma as above, the number will become 2.500.00 and if we apply now, it will become as 2,500,00.
So is there any way to convert 2,500.00 into 2.500,00 ?
String.prototype.replace can take a function:
'2,123,500.00'.replace(/[,.]/g, function(c){ return c===',' ? '.' : ','; });
You can use:
var x = '2,123,500.00';
var arr = x.split('.');
var y = arr[0].replace(/,/g, '.') + ',' + arr[1];
//=> 2.123.500,00
You're in luck, .replace() accept a function as second argument. That function has the matched string as argument and the returned value will be the replace_by value of .replace().
In short, you can simply check what the matched string is and return the right value :
var str = "2,500.00";
var changed_str = str.replace(/,|\./g, function(old){
if (old === '.')
return ',';
else if (old === ',')
return '.';
});
document.write(changed_str)
Why not use the built-in methods to format your numbers correctly?
Number.toLocaleString() would work just fine here.
If you actually have a number as you said, you can easily achieve this using the right locale. If you have a String representation of your number, you would first have to parse it.
This (now) works for any number of commas or dots, even if trailing or leading dots or commas.
HTML:
<div id="result"></div>
JS:
var x = '.,2.123,50.0.00.';
var between_dots = x.split('.');
for (var i = 0; i < between_dots.length; i++) {
between_dots[i] = between_dots[i].replace(/,/g, '.');
}
var y = between_dots.join(',');
document.getElementById('result').innerHTML = y;
Here's the JSFiddle

Incrementing a number in a string

I have the following string: 0-3-terms and I need to increment the 3 by 20 every time I click a button, also the start value might not always be 3 but I'll use it in this example..
I managed to do this using substring but it was so messy, I'd rather see if it's possible using Regex but I'm not good with Regex. So far I got here, I thought I would use the two hyphens to find the number I need to increment.
var str = '0-3-terms';
var patt = /0-[0-9]+-/;
var match = str.match(patt)[0];
//output ["0-3-"]
How can I increment the number 3 by 20 and insert it back in to the str, so I get:
0-23-terms, 0-43-terms, 0-63-terms etc.
You're doing a replacement. So use .replace.
var str = '0-3-terms';
var patt = /-(\d+)-/;
var result = str.replace(patt,function(_,n) {return "-"+(+n+20)+"-";});
Another option is to use .split instead of regex, if you prefer. That would look like this:
var str = '0-3-terms';
var split = str.split('-');
split[1] = +split[1] + 20;
var result = split.join('-');
alert(result);
I don't understand why you are using regex. Simply store the value and create string when the button is called..
//first value
var value = 3;
var str = '0-3-terms';
//after clicking the button
value = value+20;
str = "0-" + value + "-terms"

Javascript need variable that can represent any number

I'm a javascript novice so this may be a dumb question. I'm trying to generate a script that takes the phrase "(x items)" and changes it to "(x)", where x can represent any number.
Here's what I have now:
<script type="text/javascript">
$(document).ready(function(){
function changeText(){
$(".CartLink:contains('2 items')").html('Cart <span>(2)</span>');
}
changeText();
$(document).ajaxSuccess(function() {
changeText();
});
});
</script>
The above script is able to replace the phrase "(2 items)" with "(2)" but I need to modify the script so that 2 can be any number. Thank you.
This is the HTML that .CartLink element contains:
<li style="display:" class="CartLink">Cart <span>%%GLOBAL_CartItems%%</span></li>
Ideally this should be a server-side task. But if you have a limitation requiring you to do this client-side...
You don't need to replace all of the html. You can simply modify the text of the span:
$('.CartLink span').text(function(_, val) {
return val.replace(' items', '');
});
Your can use split to seperate the count and text.
http://jsfiddle.net/B2meD/
$( document ).ready(function() {
$(".CartLink").html('Cart <span>'+$(".CartLink").text().split(" ")[0]+'</span>');
});
Javascript as a string replace method. So you can simply remove the items part.
var foo = ('2 items');
var newFoo = foo.replace("items", "");
Then newFoo would become ('2')
S('.CartLink').text($('.CartLink').text().split(' ')[0])
Where are you getting the "2" variable from?
var items = 2;
items ++; //items = 3;
$('.Cart').html("Items in cart:" + items.toString() + ". Foo");
See how I added the "+" to add up the strings?
I must add, this is just bad js.
For making your items variable:
var str = "(Items 2)";
var numberStr = "(" + str.split(" ").pop(); //makes "(2)" or use .replace or whatever works.
Keep in mind that making a variable from a string will result in another string. If you want to manipulate your new items var as a number, you have to get an integer like so,
var numberStr = "(3)";
var int = parseFloat(numberStr.replace(/["'()]/g,""));
If you replace your changeText function with this it should work as you want:
function changeText() {
var itemCountSpan = $(".CartLink a span")
if (/(\d+) items/.test(itemCountSpan.text())) {
itemCountSpan.text(RegExp.$1);
}
}
Here's a simple RegEx version.
$(document).ready(function(){
function changeText(){
$(".CartLink").each(function() {
var newhtml = $(this).html().replace(/\((\d+) items\)/, "($1)");
$(this).html(newhtml);
});
}
changeText();
});
It looks at every element with the CartLink class for the string (x items) where x is one or more digits and removes the word "items". $1 is a property that gets set when the (\d+) parenthesised match is made, allowing us to use the number we want in our replacement string.

Get a number from a name

So I have objects listed like favoriteImage1, favoriteImage2... favoriteImage22. How do I get the number at the end of word? I tried parseInt but it returns undefined. Is there an easy way to do this?
Use a regular expression:
var string = "favoriteImage1";
var num = +string.replace(/\D/g, "");
If the name will always have the prefix "favoriteImage", you could also do
var x = "favoriteImage1";
var num = parseInt(x.substring(13));

adding numbers from array?

i have:
var str="100px";
var number = str.split("px");
number = number[0];
var km = "100px";
var numberk = km.split("px");
numberk = numberk[0];
var gim = numberk+100;
var kim = number+100;
var fim = number+numberk;
document.write(gim+'<br>'+kim+'<br>'+jim+'<br>');
i would be thankfull if someone could me answere why the result are added like string rather than nummerical number in javascript i have used the isNaN(); function which shows this as a legal number. So how can this problem be solved.
thanks.
You could use the parseInt function in order to convert the string returned when spliting into integer:
number = parseInt(number[0], 10);
numberk = parseInt(numberk[0], 10);
Now the 2 variables are integers and you could perform integer operations on them.
You need to put parseInt() around each number before you use it. In fact, you could do this without removing the "px".
gim = parseInt(km) + 100;
simplest way to do this, you don't need to use split.
var str="150px";
var str1 = (parseInt(str)+100)+"px";
alert(str1);
OUTPUT:
200px
fiddle : http://jsfiddle.net/Kk3HK/1/
use parseInt()
var number = parseInt(str, 10);
var numberk = parseInt(km, 10);
Use parseInt to convert the string to a number.
var str = "100px";
var number = parseInt(str, 10);
parseInt stops when it finds the first non-number character, so you don't even need to remove the "px".
Wrap the numbers in parseInt().

Categories