Tuesday, 2 October 2012

JavaScript Tips & Techniques



Table of contents:

  • Fastest way to find a value in a JavaScript array
  • Best way to trim leading zeros (from a number)
  • Character Code Conversions In JavaScript




There are many ways to skin a cat, however when it comes to writing the code (in any language), it is a good idea to benchmark or assess your code for performance, amount of effort and other issues. Even though the hardware resources are getting cheaper, which is decreasing the need of quality programmers, yet your code should still be efficient enough to run on resource-scarce mobile platforms

Considering the above, I started to compile my notes, best practices as well as snippets of code that were found to be the most efficient in most conditions, and I would like to share these with the world.


JavaScript Tips & Techniques


Fastest way to find a value in a JavaScript array

A quick way to find out if an array's element holds a value, is to convert that array into a String then simply use search() method to find what you are looking for. e.g.:

    var names = ['John','Paul','Krishna','Ali'];

Now, to test if a value exists in the array names:

    if(names.toString().search("Paul") == -1) {
      alert('True');
    }else{
      alert('False');
    }
Output: True.


Best way to trim leading zeros (from a number)

There are times when you get numbers as strings (e.g. when data is received from an html form), what if a number is received with unwanted preceding zeros (such as month-number with leading zero). Out of many ways to chop the preceding / leading zeros, one of the quickest ways is to use the parseFloat() function, following is the function I wrote today:
/**
* Chops any leading zeros (0s from the left) of the passed number as string.
* @param num the string holding number with leading zero(s) (it may come from a text-element in which number is being entered by users, this can typically be a: textbox, textarea, select, list and password.)
*/
function chopLeadingZeros(num) {
    return parseFloat(num).toFixed(0);
    // this is Quick + Clean + Short  
    //.toFixed(0) to omit decimal points if only integers are needed)
}
    //return parseInt(num); //doesn't work as leading zeros (in value) make parseInt() to treat the passed value as octal-numbers, e.g. parseInt("0101") will return 65.
    //return num.toString.replace(/^[0]+/g,""); // not good enough as it'll return "" (i.e. empty string) if only a single zero "0" is received (unless you add more statements to fix this issue).




Number Format Conversions & Unicode In JavaScript

Following covers the conversions between:

  • Decimal  to  Hex / Octal  and vice versa.
  • Unicode hex values (or ASCII upto 127)  to  Unicode Characters  and vice versa.




Decimal to Hex / Octal

Syntax: <numObj>.toString(<base>);
n = 167;
n.toString(16).toUpperCase();   // A7

Hex / Octal to Decimal

Syntax: parseInt(str,base);
hexStr='AE';
parseInt(hexStr,16);   // 174

octalStr='605';
parseInt(octalStr,8);  // 389
.

Note: When writing a hexadecimal codes, the preceding '0x' can be omitted in JavaScript functions, e.g. both 'A7' & '0xA7' are valid.


Unicode Character  to  Unicode Value (or ASCII upto 127)

Syntax: str.charCodeAt(<index>);
uniStr='æ';
uniStr.charCodeAt(0);    // 230

Unicode Value (or ASCII upto 127)  to  Unicode Character

Syntax: String.fromCharCode(<Unicode/ASCII_number>);
String.fromCharCode(65);   // A
String.fromCharCode(230);  // æ

See also:
a great article written by Paul Tero about the Character sets and Unicode.
"Using Special Characters & Character Codes" in my HTML Tips & Tricks blog.

Example explaining conversions:

<html>
<body>
<style type="text/css">p {float: left; padding:0 10px;} </style>
<script type="text/javascript">
for (var i=256; i<512; i++) 
   document.writeln(( (i%64) ? '' : '<p>') + i + ': ' +String.fromCharCode(i) +'<br>');

document.writeln(String.fromCharCode(165) + '<br>');


function toHex(d) {

return  ("0x"+(Number(d).toString(16).toUpperCase() ) );
}

document.writeln ('<hr> <b>Hex/Octal to Decimal</b>' +'<br>');

hexStr='A3';
decNum = parseInt(hexStr,16);   // decNum now holds 163
document.writeln ("hex: " +hexStr +" = decimal: " + decNum + '<br>');

hexStr0x='0xA3';

decNum = parseInt(hexStr0x,16);   // decNum now holds 163
document.writeln ("hex: " +hexStr0x +" = decimal: " + decNum + '<br>');

octalStr='243';

decNum = parseInt(octalStr,8);  // decNum now holds octal: 389
document.writeln ("octal: " +octalStr + " = decimal:  " + decNum + '<br>');

document.writeln ('<hr> <b>Decimal to Hex/Octal</b>' +'<br>');

n = 163;
hexStr = n.toString(16).toUpperCase();
document.writeln ("Decimal: " +n +" = Hex: " +hexStr +'<br>');

octStr = n.toString(8).toUpperCase();

document.writeln ("Decimal: " +n +" = Octal: " +octStr +'<br>');

document.writeln ('<hr> <b>Unicode to Unicode-Character</b>' +'<br>');

n="230";
uni = String.fromCharCode(n);
document.writeln ("Unicode: " +n +" = Char: " +uni + '<br>');

document.writeln ('<hr> <b>Unicode-Character to Unicode</b>' +'<br>');

uniStr='æ';
decNum = uniStr.charCodeAt(0);
document.writeln ("Char: " +uniStr +" = Unicode:  " + decNum + '<br>');

</script>

</body>
</html>