Jalaj P. Jha Technical & Miscellaneous Ramblings

8Mar/074

Asc() and Chr() in JavaScript

I have mostly coded in languages in VB family i.e. VB, VBA, VBScript, ASP. So when I needed to code in JavaScript, I was left with no choice but to Google for JavaScript equivalents for Asc() and Chr() functions, which I badly required to use for my assignment. And what I came up with is as described below.

The Asc() and Chr() functions as exist with VB languages are available as resp. charCodeAt() and fromCharCode() methods of string object.

While Asc() function in VBScript returns ASCII value for the first character of the string, charCodeAt method takes for parameter an index and returns ASCII code for character at given index in the string. So if you need to get ASCII value for the first character just pass 0 for the parameter.

If you still think that you prefer VB style, why not code functions that work and return values similar to VB functions. This will also illustrate the usage of the equivalent JavaScript functions.

<script>
function Asc(String)
{

	return String.charCodeAt(0);

}

function Chr(AsciiNum)
{

	return String.fromCharCode(AsciiNum)

}
</script>

On Technorati :

Comments (4) Trackbacks (5)
  1. Hey, thank you! I’m a VB user trying to understand JavaScript :P

  2. when my charset is gb2312(chinese),the result is wrong

  3. its working Thank you!!

  4. hey this converts upper to lower case and vice versa man


Leave a comment

(required)

  • Twitter
  • Buzz
  • Facebook
  • Orkut
  • Picasa
  • YouTube