How can I convert this into a integer in Javascript? - javascript

I asked a similar question yesterday .. If I have for example 0-9999 , how can I turn this into 09999 , basically removing the - and make it an integer in javascript ?
var = 0-9999
turn that into 9999 integer
or var = 2-9999 , turn that into 29999
Thanks a bunch

This should do the trick:
num = num.replace(/[^0-9]+/g, '') * 1;
It'll strip out any non-numeric characters and convert the variable into an integer. Here's a jsFiddle demonstration for you.

The most obvious and basic of solutions would be:
var s = "1-2345";
var t = s.replace("-","");
var i = parseInt(t,10);
But that's making a lot of assumptions and ignoring any errors.

Try this:
var i = '0-9999';
var int = Number(i.replace('-', ''));
window.alert(int);
Note in Firefox, parseInt() won't work with leading zeros unless you pass in a radix (this appears to be a bug):
var int = parseInt(i.replace('-', ''), 10);
Fiddler

Remember that
var x = 2-9999
is the same as
var x = -9997
because the dash is seen as a subtraction symbol unless you use quotation marks (Single or double, doesn't matter).
So, assuming that you properly quote the text, you can use the following function to always pull out a character that is in any given spot of the text (Using a zero-based index).
function extractChar(myString,locationOfChar){
var y = myString.substring(0,locationOfChar-1)
var z = myString.substring(locationOfChar+1)
var s = y.concat(z)
var i = parseInt(s,10)
return i
}
therefore
var i = extractChar("2-9999",1)
Will be the same as
var i = 29999

Related

Javascript calculation giving wrong answer because of comma

I have a calculation which works fine until it hits a thousand separator, which is a comma. I have tried a few things trying to get rid of the comma but I can't seem to get it right. Below is the last thing I tried which was a total failure. The 'tot_amount' is the one I need the comma stripped from. I think I went down the wrong track and it should be doable without the extra 'tot' variable. Please assist.
function updateDue() {
var total = parseInt(document.getElementById("tot_amount").value);
var val2 = parseInt(document.getElementById("eftposamount").value);
var tot = total.replace(",","");
// to make sure that they are numbers
if (!tot) { tot = 0; }
if (!val2) { val2 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = tot - val2;
}
Replacing
Your code is only removing one comma, try using this instead:
total.replace(/,/g, "");
The best way is to remove all non-number safe stuff and use that:
+total.replace(/[^\de.-]/gi, "")
As you see I've a g
The g stands for global meaning it will replace all commas instead of just the first one.
String to Integers
Instead of:
var total = parseInt(document.getElementById("tot_amount").value);
var tot = total.replace(",","");
You must make it an integer after you parse it. A short way to parse a number is using +
var total = +document.getElementById("tot_amount").value.replace(/[^\de.-]/gi, "")
Your code:
You can make your function this:
function updateDue() {
document.getElementById("remainingval").value =
+document.getElementById("tot_amount").value.replace(/[^\de.-]/gi, "") -
+document.getElementById("eftposamount").value.replace(/[^\de.-]/gi, "")
|| 0
}
The ||0 will remove the need for the ifs.
Calling parseInt on a comma-delimited string will give you unexpected results:
parseInt('1,000'); // => 1
Instead, you want to remove commas, and then parse the integer:
var i = +('1,000'.replace(/,/g, '')); // => 1000
The // part is simply RegExp notation, and the g afterwards is a flag that tells the parser to look for global instances of the expression. In your case, you want to remove all commas, so the g flag is appropriate.
For the sake of saving 7 characters in your code, you can simply coerce your value to an integer with + rather than calling parseInt.

Dynamic regex pattern in JavaScript

I have some code that matches a certain number of digits after a decimal. Currently, I have the following:
var input = getValueFromUser();
var count = getCount();
var x = Number(input.toString().match(/^\d+(?:\.\d{0,1})?/));
alert(x);
This approach always gets the first digit after the decimal. However, I want to replace the 1 in the regex with the value in count. How do I do that? I tried the following:
var pattern = '/^\d+(?:\.\d{0,' + count + '})?/';
var x = Number(input.toString().match(pattern));
However, now, I always get 0 for x.
You have to use Regexp object if you want to use dynamically built patterns:
var re = new RegExp('^\\d+(?:\\.\\d{0,' + count + '})?');
This will help you.
var pattern = '^\\d+(?:\\.\\d{0,' + '5' + '})?',
reg=new RegExp(pattern),
x = Number(input.toString().match(reg));
mask: new RegExp(`^[a-zA-Z0-9]{0,${maxLength}}$`)
its work for me
var alien = 'ajay'+' $%';
var all=new RegExp(`${alien}`)

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"

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