Saturday 25 January 2014

string object

A string simply stores a series of characters like "John Doe".

A string can be any text inside quotes. You can use single or double quotes:

syntax:
var val = new String(string);

Property
Description
Returns a reference to the String function that created the object.
Returns the length of the string.
The prototype property allows you to add properties and methods to an object.
Returns the character at the specified index.
Returns a number indicating the Unicode value of the character at the given index.
Combines the text of two strings and returns a new string.
Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.
Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.
Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
Used to match a regular expression against a string.
Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.
Executes the search for a match between a regular expression and a specified string.
Extracts a section of a string and returns a new string.
Splits a String object into an array of strings by separating the string into substrings.
Returns the characters in a string beginning at the specified location through the specified number of characters.
Returns the characters in a string between two indexes into the string.
The characters within a string are converted to lower case while respecting the current locale.
The characters within a string are converted to upper case while respecting the current locale.
Returns the calling string value converted to lower case.
Returns a string representing the specified object.
Returns the calling string value converted to uppercase.
Returns the primitive value of the specified object.
<!DOCTYPE html>
<html>
<body>

<script>
var carname1="Volvo XC60";
var carname2='Volvo XC60';
var answer1="It's alright";
var answer2="He is called 'Ram'";
var answer3='He is called "Ravi"';

document.write(carname1 + "<br>")
document.write(carname2 + "<br>")
document.write(answer1 + "<br>")
document.write(answer2 + "<br>")
document.write(answer3 + "<br>")
</script>

</body>

<!--http://improvejavascript.blogspot.in/ -->
</html>
//match()
<!DOCTYPE html>
<html>
<body>

<script>

var str="Hello world!";
document.write(str.match("world") + "<br>");
document.write(str.match("World") + "<br>");
document.write(str.match("world!"));

</script>

</body>
<!output is:world
null
world!-->

</html>
//toUpperCase() method
<!DOCTYPE html>
<html>
<body>

<script>

var txt="Hello World!";
document.write("<p>" + txt.toUpperCase() + "</p>");
document.write("<p>" + txt.toLowerCase() + "</p>");
document.write("<p>" + txt + "</p>");

</script>

<p>
The methods returns a new string.
The original string is not changed.
</p>
</body>
</html>
//split() method

<!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to display the array values after the split.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
var str="a,b,c,d,e,f";
var n=str.split(",");
document.getElementById("demo").innerHTML=n[0];
}
</script>


</body>


</html>
//Ex2 for split method
<!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to display the array values after the split.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
var str="a,b,c,d,e,f";
var n=str.split(",");
document.getElementById("demo").innerHTML=n[0];
}
</script>


</body>


</html>

//Ex3 for String object
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>

<script>
var x = "Ram";              // x is a string
var y = new String("Ram");  // y is an object
var txt = typeof(x) + " " + typeof(y);
document.getElementById("demo").innerHTML=txt;
</script>

</body>


</html>

Boolean object

The Boolean object represents two values either "true" or "false".
Syntax:
Creating a boolean object:
var val = new Boolean(value);
If value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.
Boolean Properties:
Here is a list of each property and their description.
Property
Description
Returns a reference to the Boolean function that created the object.
The prototype property allows you to add properties and methods to an object.
Boolean Methods
Here is a list of each method and its description.
Method
Description
Returns a string containing the source of the Boolean object; you can use this string to create an equivalent object.
Returns a string of either "true" or "false" depending upon the value of the object.
Returns the primitive value of the Boolean object.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<script type="text/javascript">
 var b1=new Boolean();
 var b2=new Boolean(0);
 var b3=new Boolean(1);
 var b4=new Boolean(true);
 var b5=new Boolean(false);
 var b6=new Boolean("");
 var b7=new Boolean("abc");
 var b8=new Boolean("null");

 document.write("b1 :"+b1+"<br/>");
 document.write("b2 :"+b2+"<br/>");
 document.write("b3 :"+b3+"<br/>");
 document.write("b4 :"+b4+"<br/>");
 document.write("b5 :"+b5+"<br/>");
 document.write("b6 :"+b6+"<br/>");   
 document.write("b7 :"+b7+"<br/>"); 
 document.write("b8 :"+b8+"<br/>");  
</script> 
</body>
</html>
<! --b1 :false
b2 :false
b3 :true
b4 :true
b5 :false
b6 :false
b7 :true
b8 :true -->

Number Object

·         JavaScript has only one type of number.
·         Numbers can be written with, or without decimals.
·          
Example
·         var pi=3.14;    // A number written with decimals
var x=34;       // A number written without decimals
Extra large or extra small numbers can be written with scientific (exponent) notation:
Example
var y=123e5;    // 12300000
var z=123e-5;   // 0.00123

Number Properties
  • MAX_VALUE
  • MIN_VALUE
  • NEGATIVE_INFINITY
  • POSITIVE_INFINITY
  • NaN
  • prototype
  • constructor
All number properties are properties of JavaScripts' number object wrapper called Number.
These properties can only be accesses as Number.MAX_VALUE.
Using num.MAX_VALUE, where num is a created object or a primitive number value, will return undefined.


Number Methods
  • toExponential()
  • toFixed()
  • toPrecision()
  • toString()
  • valueOf()
Note: Primitive values, like 3.14, cannot have properties and methods (because they are not objects).
With JavaScript, all methods of the number object are also available to primitive values, because Javascript will temporarily transfer primitive values to objects before executing the methods.


Numbers Can be Numbers or Objects

JavaScript numbers can be primitive values created from literals, like var x = 123;
JavaScript number can also be objects created with the new keyword, like var y = new Number(123);

Example

var x = 123;
var y = new Number(123);
typeof(x) // returns Number
typeof(y) // returns Object
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>

<script>
var x = 123;              // x is a number
var y = new Number(123);  // y is an object
var txt = typeof(x) + " " + typeof(y);
document.getElementById("demo").innerHTML=txt;
</script>

</body>


</html>
Normally, because of some nasty side effects, you will not define numbers as objects.

Example

var x = 123;              
var y = new Number(123);
(x === y) // is false because x is a number and y is an object.



Ex:
<!Number object>
<html>
<body>

<script>

var x;
document.write("<p>Only 17 digits: ");
x=12345678901234567890;
document.write(x + "</p>");

document.write("<p>0.2 + 0.1 = ");
x=0.2+0.1;
document.write(x + "</p>");

document.write("<p>It helps multiplying and dividing by 10: ");
x=(0.2*10+0.1*10)/10;
document.write(x +"</p>");

</script>

</body>

<!-- http://improvejavascript.blogspot.in/ -->
</html>

Ex:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>

<script>
var x = 123;              // x is a number
var y = new Number(123);  // y is an object
var txt = typeof(x) + " " + typeof(y);
document.getElementById("demo").innerHTML=txt;
</script>

</body>


</html>

Ex3:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>

<script>
var x = 123;              // x is a number
var y = new Number(123);  // y is an object
document.getElementById("demo").innerHTML = x===y;
</script>

</body>


</html>

example program for throw keyword

<!DOCTYPE html>
<html>
<body>

<script>
function myFunction()
{
var y=document.getElementById("mess");
y.innerHTML="";
//try
//{
var x=document.getElementById("demo").value;
if(x=="")    throw "empty";
if(isNaN(x)) throw "not a number";
if(x>10)     throw "too high";
if(x<5)      throw "too low";
//}
//catch(err)
//{
y.innerHTML="Error: " + err + ".";
//}
}
</script>

<h1>My First JavaScript</h1>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="mess"></p>

</body>


</html>


Example 2:
<!DOCTYPE html>
<html>
<body>

<script>
function myFunction()
{
var y=document.getElementById("mess");
y.innerHTML="";

var x=document.getElementById("demo").value;
if(x=="")   document.writeln( "empty");
if(isNaN(x)) document.writeln("not a number");
if(x>10)   document.writeln( "too high");
if(x<5) document.writeln("too low");

//y.innerHTML="Error: " + err + ".";
//}
}
</script>

<h1>My First JavaScript</h1>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="mess"></p>

</body>

</html>



Exception Handling

Syntax errors:
Syntax errors, also called parsing errors, occur at compile time for traditional programming languages and at interpret time for JavaScript.
For example, the following line causes a syntax error because it is missing a closing parenthesis:
<script type="text/javascript">
<!--
window.print(;
//-->
</script>
When a syntax error occurs in JavaScript, only the code contained within the same thread as the syntax error is affected and code in other threads gets executed assuming nothing in them depends on the code containing the error.
Runtime errors:
Runtime errors, also called exceptions, occur during execution (after compilation/interpretation).
For example, the following line causes a run time error because here syntax is correct but at run time it is trying to call a non existed method:
<script type="text/javascript">
<!--
window.printme();
//-->
</script>
Exceptions also affect the thread in which they occur, allowing other JavaScript threads to continue normal execution.
Logical errors:
Logic errors can be the most difficult type of errors to track down. These errors are not the result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your script and you do not get the result you expected.
You can not catch those errors, because it depends on your business requirement what type of logic you want to put in your program.
The try...catch...finally Statement:
The latest versions of JavaScript added exception handling capabilities. JavaScript implements the try...catch...finally construct as well as the throw operator to handle exceptions.
You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax errors.
Here is the try...catch...finally block syntax:
<script type="text/javascript">
<!--
try {
    // Code to run
    [break;]
} catch ( e ) {
    // Code to run if an exception occurs
    [break;]
}[ finally {
    // Code that is always executed regardless of
    // an exception occurring
}]
//-->
</script>
The try block must be followed by either exactly one catch block or one finally block (or one of both). When an exception occurs in the try block, the exception is placed in e and the catchblock is executed. The optional finally block executes unconditionally after try/catch.
Examples:
Here is one example where we are trying to call a non existing function this is causing an exception raise. Let us see how it behaves without with try...catch:
<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
   var a = 100;

   alert("Value of variable a is : " + a );

}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
To understand it in better way you can Try it yourself.
Now let us try to catch this exception using try...catch and display a user friendly message. You can also suppress this message, if you want to hide this error from a user.
<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
   var a = 100;
  
   try {
      alert("Value of variable a is : " + a );
   } catch ( e ) {
      alert("Error: " + e.description );
   }
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
To understand it in better way you can Try it yourself.
You can use finally block which will always execute unconditionally after try/catch. Here is an example:
<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
   var a = 100;
  
   try {
      alert("Value of variable a is : " + a );
   }catch ( e ) {
      alert("Error: " + e.description );
   }finally {
      alert("Finally block will always execute!" );
   }
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
To understand it in better way you can Try it yourself.
The throw Statement:
You can use throw statement to raise your built-in exceptions or your customized exceptions. Later these exceptions can be captured and you can take an appropriate action.

Syntax

throw exception
The exception can be a JavaScript String, a Number, a Boolean or an Object.
Following is the example showing usage of throw statement.
Ex1:
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction()
{
var y=document.getElementById("mess");
y.innerHTML="";
try
{
var x=document.getElementById("demo").value;
if(x=="")    throw "empty";
if(isNaN(x)) throw "not a number";
if(x>10)     throw "too high";
if(x<5)      throw "too low";
}
catch(err)
{
y.innerHTML="Error: " + err + ".";
}
}
</script>
<h1>My First JavaScript</h1>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="mess"></p>
</body>
</html>



<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
   var a = 100;
   var b = 0;
  
   try{
      if ( b == 0 ){
         throw( "Divide by zero error." );
      }else{
         var c = a / b;
      }
   }catch ( e ) {
      alert("Error: " + e );
   }
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
You can raise an exception in one function using a string, integer, Boolean or an object and then you can capture that exception either in the same function as we did above, or in other function using try...catch block.
The onerror() Method
The onerror event handler was the first feature to facilitate error handling for JavaScript. Theerror event is fired on the window object whenever an exception occurs on the page. Example:
<html>
<head>
<script type="text/javascript">
<!--
window.onerror = function () {
   alert("An error occurred.");
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
To understand it in better way you can Try it yourself.
The onerror event handler provides three pieces of information to identify the exact nature of the error:
  • Error message . The same message that the browser would display for the given error
  • URL . The file in which the error occurred
  • Line number . The line number in the given URL that caused the error
Here is the example to show how to extract this information
<html>
<head>
<script type="text/javascript">
<!--
window.onerror = function (msg, url, line) {
   alert("Message : " + msg );
   alert("url : " + url );
   alert("Line number : " + line );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
You can display extracted information in whatever way you think it is better.
To understand it in better way you can Try it yourself.
You can use onerror method to show an error message in case there is any problem in loading an image as follows:
<img src="myimage.gif"
    onerror="alert('An error occurred loading the image.')" />

You can use onerror with many HTML tags to display appropriate messages in case of errors.