I'm just starting javascript and jquery and now I'm stuck with this kind of problem:
var myCharacter = ('#myCharacter').css('top'); // gives 140px
var numberOnly = myCharacter.replace('px',''); // gives 140
var total = numberOnly + 20; // gives 14020 not 160
I just don't understand why this happens.
you need parseInt()
var total = parseInt(numberOnly) + 20;
because numberOnly is a string, not a number, so its adding a number to a string which results in that 14020 as a string
When you replace 'px' in '140px', you end up with a variable of string type. (javascript has types, but they are dynamic)
When you call '140'+20, the type is not converted automatically, because + is an operation that makes sense on strings: concatenation.
You should explicitly convert to a number, for example by using parseInt('140'), then the addition should work as expected.
As one of the operands in numberOnly + 20 is a string, the + operator does string concatenation, not addition.
Use the parseInt method to parse the string to a number, then you don't have to remove the px part either, as the parsing ends when it encounters non-numerical characters.
var myCharacter = parseInt(('#myCharacter').css('top'), 10);
var total = myCharacter + 20;
That's because numberOnly is a String you can cast to int by doing:
var total = +numberOnly + 20
var myCharacter = ('#myCharacter').css('top'); // gives 140px
var numberOnly = myCharacter.replace('px',''); // gives 140
var total = parseInt(numberOnly) + 20;
you are trying to add up with string so first convert it into integer,use parseInt() to do this:
var total = parseInt(numberOnly) + 20;//160
numberOnly is still of type string, i.e. it's a number of characters. Thus you currently conctenate string '140' with 20, which is implicitly converted to a string.
To fix this, convert numberOnly to an integer using [parseInt][1].
Related
var name = $(".column_nr_matching:last").attr("name");
// this gives me col_nr359
and here I add plus 1
var added_one = name + (+1);
When I look with console it gives me this:
col_nr3591
I need it to be
col_nr360
Because col_nr359 is a string, and by using +, you are concatenating 1 to that string. You need to do something like this:
document.getElementById('increment').onclick = function (){
//get the innertext from the span
var text = document.getElementById('colid').innerText;
//replace the 'col_nr' text with empty string to get the number
var nr = text.replace('col_nr','');
//parses the number to int and sums 1, then concatenate back
var new_id = 'col_nr' + (parseInt(nr) + 1);
//set the new text to the span
document.getElementById('colid').innerText = new_id;
}
<span id="colid">col_nr359</span>
<br>
<button id="increment" > Increment </button>
As mentioned, name is a string, not a number. You need to just get the number part so you can add one to it. One possible way of doing so is with a regex string replace, where you use capture group to get the number part, and replace it with that number plus one. Example:
const name = "col_nr359";
const added_one = name.replace(/(\d*)$/, m => String(+m + 1))
console.log(added_one)
col_nr359 is a String, even JavaScript can't interpret it as number, since there are characters in front.
What you have to do is split the string so you have col_nr and 359, then add 1 to the 359, then concatenate it again.
You are mixing datatypes. col_nrxxx is a string and will always be one. You have to cut out the 359, then parse it to int, then add the +1, then concat it back to the string.
When you first learn to code, you learn there are different value types. Strings, like "Hello", booleans, like true, and numbers, like 1. How can I set the value of a <p> tag to be a number and not a string? Or is there a separate number tag?
Javascript is an untyped language. The variable type is deduced from the value of that variable. The type of a variable could also change a value of another type is assigned to it. So things like this (for example C language):
int a; // a is an int (it will be always an int)
float f = 5.34; // f is a float (it will always be a float)
do not exist in Javascript. Javascript could use the same variable to store multiple types without redeclaring the variable.
var a = 45; // a type is deduced from the current assignement so for now it's a number
a = "string"; // now the type of a is a string not a number anymore
You can explicitly or implicitly convert one type to another when needed.
Explicit Conversation:
you can convert a number into a string (although it will not be necessary) using .toString like this:
var num = 456;
console.log("num is of type: " + typeof(num));
var str = num.toString(); //explicitly change num to string
console.log("str is of type: " + typeof(str));
You can also convert a string into a number explicitly (this is used a lot) using parseInt if the string is an integer, parseFloat if the string is a float, or Number to get any like this:
var str = '123.45.99';
console.log("str is of type: " + typeof(str));
var num1 = parseInt(str); // will parse an integer untill the first non integer character is found (will return 12 if str == "12ppp")
console.log("num1 is of type: " + typeof(num1));
var num2 = parseFloat(str); // parses a float untill the first non float character is found (will return 75.56 if str == "75.56.55abc"
console.log("num2 is of type: " + typeof(num2));
var num3 = Number(str); // get number representation of the string (will fail (return NaN) if the string is not a valid number like "123r33")
console.log("num3 is of type: " + typeof(num3));
Implicit Conversation:
Implicit conversation is when you let for the interpretter no other choice except of handling your variable as of your type. Thus preventing it from interpretting them incorrectly. You can acheive this using a lot of ways.
To implicitly convert a number into a string, just add an empty string to that number like this:
var num = 345;
console.log("num is of type: " + typeof(num));
var str = "" + num;
console.log("str is of type: " + typeof(str));
To convert a string into a number, there are multiple ways like this:
var str = '123.45';
console.log("str is of type: " + typeof(str));
var num1 = +str; // a unary operator (that is valid for numbers only) forces the interpretter to use the value of str as a number
console.log("num1 is of type: " + typeof(num1));
Since the + operator (not the unray one) could be used for both concatenation and the addition the interpretter will always favor the concatenation on the addition if one of the operands is a string. But the other operator (/, *, / and %) are only used for number, so when a string is divided by another number, the interpretter will be forced to use the value of the string as a number:
var str = "10";
var num1 = str + 5;
console.log("num1 is: " + num1 + " and it's of type: " + typeof(num1)); // print out the wrong expectation, because since one of the operands of the + is a string (str) the interpretter will think it's a concatenation
var num2 = str * 5; // since * could be used with just numbers, the interpretter is forced to use str as a number (implicitly converting str to a number)
console.log("num2 is: " + num2 + " and it's of type: " + typeof(num2));
// to make the + operator work you'll have to use the unary operator to implicitly convert str before adding the numbers
var num3 = +str + 5;
console.log("num3 is: " + num3 + " and it's of type: " + typeof(num3));
// ++ and -- are also used with just number ..
str++; // since str++ is str = something and that something is calculated as number str will implicitly take the value of a number thus when used again it will be deduced as a number
console.log("str is: " + str + " and it's of type: " + typeof(str)); // in the previous assignment, str took the value of a number thus becoming a number
HTML <p> tag specifically stands for paragraphs. So it is supposed to treat everything inside it as strings of text.
If you are sure it contains numerical value, you can convert it to a number using parseFloat(yourPtext.replace(',','')); and use it in your javascript code.
Assuming that you are using the <p> parameter as a paragraph of text..
Try wrapping the <p></p> in side a <div>
Then give it an id.
Like this:
<div id="myClass"><p></p></div>
Then add some javascript like so:
<script>
var element = document.getElementById("myClass");
element.innerText = "1";
</script>
Might want to to look at this link
http://www.w3schools.com/js/js_htmldom_html.asp
The <p> is the element used to wrap paragraphs. The value of a <p> tag is always text. Checking W3C HTML5 standard, you discover that the content model for <p> element is Phrasing content:
Phrasing content is the text of the document, as well as elements that mark up that text at the intra-paragraph level. Runs of phrasing content form paragraphs.
So, you can display numbers inside a <p> element but they are always represented as strings. You can get the value of a paragraph as a string and then parse it to a number:
var par = document.getElementById('p1');
var val = par.innerHTML;
console.log('val:', typeof val); // Return "string"
var valNumber = parseInt(val); // Parsing the string value to integer
console.log('valNumber:', typeof valNumber); // Return "number"
<p id="p1">123</p>
Using jquery you can do so in 2 ways
1) var pText = $("p").text()
var number = Number(pText)
2) var pText = $("p").text()
var number = parseInt(pText,10)
or replace <p> tag with <input type="number" value="" >
I need to remove the dot in 1.400 in order to get the integer 1400, but it return 140. How do I obtain 1400 as an integer?
var var2= String(1.400) ;
var2 = var2.replace(".","");
var2=parseInt(var2);
There's no way the code you've given returns 140, since 1.400 is a number literal and gets shortened to 1.4 straight away and only then turned to string of "1.4". Therefore replacing a dot and converting to int results in 14.
It's not possible to tell JavaScript that number of 1.400 is not 1.4. You'd have to start with a string of "1.400" to get what you want.
Instead of going number -> string -> number maybe you could multiply the number by a thousand, or whatever order of magnitude is required.
Here is the problem ,
var var2= String(1.400) ;
alert(var2); //Returns 1.4 cause it is performing Number to String conversion
So , Change it to var var2= "1.400"; or var var2=number.toString();
And Update the replace to
var2.replace(/\./g,""); // : /g means all occurrence
You need to escape the . because it has the meaning of an arbitrary character in a regex.
Using this you will get your expected output.
var var2= "1.400" ;
var2 = var2.replace(".","");
var2=parseInt(var2);
Explanation:
var s1 = '2 + 2'; // creates a string primitive
var s2 = new String('2 + 2'); // creates a String object
console.log(eval(s1)); // returns the number 4
console.log(eval(s2)); // returns the string "2 + 2"
Add single-quotes around the initial string:
var var2= String('1.400');
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().
I have one string which contain number and character. I need to separate number and character. I have don't have a delimiter in between. How can I do this.
Var selectedRow = "E0";
I need to "0" in another variable.
Help me on this.
Depends on the format of the selected row, if it is always the format 1char1number (E0,E1....E34) then you can do:
var row = "E0";
var rowChar = row.substring(0, 1);
// Number var is string format, use parseInt() if you need to do any maths on it
var number = row.substring(1, row.length);
//var number = parseInt(row.substring(1, row.length));
If however you can have more than 1 character, for example (E0,E34,EC5,EDD123) then you can use regular expressions to match the numeric and alpha parts of the string, or loop each character in the string.
var m = /\D+(\d+)/gi.exec(selectedRow);
var row = m.length == 2 ? m[1] : -1;
selectedRow.charAt(1)
Becomes more complex if your example is something longer than 'E0', obviously.