adding numbers from array? - javascript

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().

Related

Javascript append colon to numbers of unknown length?

I have a number let's say
305060
And I want to put a : at the -2 and -4 spot so I end up with
30:50:60
And if I entered 5006070 I would end up with 500:60:70
I can't seem to figure out how to do this.
Use this code:
var number = 123456789;
var formatted = number.toString().replace(/^(\d+)(\d{2})(\d{2})/, '$1:$2:$3');
alert(formatted);
Demo: http://jsfiddle.net/U4J6n/
If number is a string, you can remove the .toString() method from the code.
You could use a regex that catches the two last groups of two numbers
/(\d{2})(\d{2})$/
so it's
var x = 305060;
x = x.toString().replace(/(\d{2})(\d{2})$/, ":$1:$2"); // 30:50:60
var x2 = 5006070;
x2 = x2.toString().replace(/(\d{2})(\d{2})$/, ":$1:$2"); // 500:60:70
FIDDLE
Lets suppose n is the length of the string, first you want to take the number from 0 to n-4 then n-4 to n-2 and finally n-2 to n, so simply use one of substring or slice to get the solution.
If you want to use substring then it would be
var num="305060";
var length=num.length;
var ans=num.substring(0,length-4)+":"+num.substring(length-4,length-2)+":"+num.substring(length-2,length);
alert(ans);
If you want to use slice then
var num="305060";
var length=num.length;
var ans=num.slice(0,length-4)+":"+num.slice(length-4,length-2)+":"+num.slice(length-2,length);
alert(ans);
substr is another function in javascript which will help you to get the solution
var num="305060";
var length=num.length;
var ans=num.substr(0,length-4)+":"+num.substr(length-4,2)+":"+num.substr(length-2,2);
alert(ans);
You can use String.prototype.slice
Javascript
var x = 305060,
y = x.toString(),
z = [y.slice(0, -4), y.slice(-4, -2), y.slice(-2)].join(':');
console.log(z);
Output
30:50:60
On jsFiddle

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

Can't convert string to number javascript what is wrong with my code?

var d_long;
var d_lat;
a = "37.333941,-121.879065";
var comma = a.search(",");
d_lat = a.slice(0,comma);
d_long = a.slice(comma+1,-1);
Math.floor(d_lat);
Math.floor(d_long);
alert(d_lat + " " + d_long);
var x = d_lat+d_long;
alert(x);
Thanks guys I understand what I was doing wrong. I will try split instead of my weird splice. I think I will use d_lat = Number(d_lat);
You need to use parseFloat - see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat
Math.floor does not transform the input, it returns the number.
d_lat = Math.floor(d_lat);
Should do it.
This works:
...
var x = Number(d_lat)+Number(d_long);
...
See http://www.w3schools.com/jsref/jsref_number.asp
parseFloat you need to use. Also you can on string use split(','), rather this weird slicing

Extract numbers from a string using javascript

I'd like to extract the numbers from the following string via javascript/jquery:
"ch2sl4"
problem is that the string could also look like this:
"ch10sl4"
or this
"ch2sl10"
I'd like to store the 2 numbers in 2 variables.
Is there any way to use match so it extracts the numbers before and after "sl"? Would match even be the correct function to do the extraction?
Thx
Yes, match is the way to go:
var matches = str.match(/(\d+)sl(\d+)/);
var number1 = Number(matches[1]);
var number2 = Number(matches[2]);
If the string is always going to look like this: "ch[num1]sl[num2]", you can easily get the numbers without a regex like so:
var numbers = str.substr(2).split('sl');
//chop off leading ch---/\ /\-- use sl to split the string into 2 parts.
In the case of "ch2sl4", numbers will look like this: ["2", "4"], coerce them to numbers like so: var num1 = +(numbers[0]), or numbers.map(function(a){ return +(a);}.
If the string parts are variable, this does it all in one fell swoop:
var str = 'ch2fsl4';
var numbers = str.match(/[0-9]+/g).map(function(n)
{//just coerce to numbers
return +(n);
});
console.log(numbers);//[2,4]
As an alternative just to show how things can be achieved in many different ways
var str = "ch2sl10";
var num1 = +(str.split("sl")[0].match(/\d+/));
var num2 = +(str.split("sl")[1].match(/\d+/));
Try below code
var tz = "GMT-7";
var tzOff = tz.replace( /[^+-\d.]/g, '');
alert(parseInt(tzOff));

How can I convert this into a integer in 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

Categories