2

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

3
  • +str or parseInt(str, 10) or Number(str), and don't forget about NaN which you will get for invalid numbers Commented Jun 8, 2015 at 21:52
  • 4
    Are you looking for if a string has numerals IN it, or what the character count is of the string? Commented Jun 8, 2015 at 21:53
  • 2
    I think you have to expand on the "numeric value of string" part. Commented Jun 8, 2015 at 22:00

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I like this but in the interest of being a complete answer I created a fiddle that expands on this a little bit. It checks if the string is a number. If not it defaults to 0. jsfiddle.net/0gj5v891
1

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

Comments

0

I'm thinking he wants a numeric value of a String so that he can later change it back into the same word

maybe from String to Binary to Numeric and vice-versa ?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.