I would like to get the numeric value of any string in javascript. How would I go about this?
Ex: string = "what is my numeric value"
I am wanting the numeric value of string?
Thanks....
If you're looking for an integer version of a string that contains a number, then like so:
var string = '3';
var stringNum = parseInt( string ); // 3
If you're looking for the number of characters in a string, then:
var string = 'hello test one two';
var stringLength = string.length; // 18
EDIT: One more thing to call out. If you run parseInt() that isn't a number, you'll get NaN as a result.
As it's not exactly clear what you want, here is a function that gives you an Array of the char codes of the string
function strToCharCode(str) {
return Array.prototype.map.call(str, function(e){return e.charCodeAt(0);});
}
strToCharCode("what is my numeric value");
/*
[
119, 104, 97, 116, 32, 105, 115, 32,
109, 121, 32, 110, 117, 109, 101, 114,
105, 99, 32, 118, 97, 108, 117, 101
]
*/
Please note that internally JavaScript uses UCS-2, which is similar to UTF-16, using 16-bit encoding (not 8 bit) so non-latin characters may have values up to 65535
+strorparseInt(str, 10)orNumber(str), and don't forget aboutNaNwhich you will get for invalid numbers