Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Javascript String Constructor

String is the built-in object corresponding to the primitive string data type. It contains a very large number of methods for string manipulation and examination, substring extraction, and even conversion of strings to marked-up HTML, though unfortunately not standards-oriented XHTML.

The String() constructor takes an optional argument that specifies its initial value:

var s = new String();

var headline = new String("Dewey Defeats Truman");


Because you can invoke String methods on primitive strings, programmers rarely create String objects in practice.

The only property of String is length, which indicates the number of characters in the string.

var s = "String fun in JavaScript";

var strlen = s.length;

// strlen is set to 24


The length property is automatically updated when the string changes and cannot be set by the programmer. In fact there is no way to manipulate a string directly. That is, String methods do not operate on their data “in place.” Any method that would change the value of the string, returns a string containing the result. If you want to change the value of the string, you must set the string equal to the result of the operation. For example, converting a string to uppercase with the toUpperCase() method would require the following syntax:

var s = "abc";

s = s.toUpperCase();

// s is now "ABC"
Invoking s.toUpperCase() without setting s equal to its result does not change the value of s. The following does not modify s:

var s = "abc";

s.toUpperCase();

// s is still "abc"
Other simple string manipulation methods such as toLowerCase() work in the same way; forgetting this fact is a common mistake made by new JavaScript programmers.

JavaScript String Split Function

split()

The split() method splits (for lack of a better word) a string up into substrings and returns them in an array. It accepts a string or regular expression argument containing the delimiter at which the string will be broken.

<script type="text/javascript">
var testString = "It is very nice script";

var testSplitResult = testString.split(" ");

for(i = 0; i < testSplitResult.length; i++){
    document.write("<br /> Element " + i + " = " + testSplitResult[i]);
}
</script>

JavaScript Redirect

<script type="text/javascript">

window.location = "http://www.yoursite.com/"

</script>

JavaScript System Dialogs alert(),confirm(),prompt()

The browser is capable of invoking system dialogs to display to the user through the alert(),
confirm(), and prompt() methods. These dialogs are not related to the web page being displayed
in the browser and do not contain HTML. Their appearance is determined by operating system and/
or browser settings rather than CSS. Additionally, each of these dialogs is synchronous and modal,
meaning code execution stops when a dialog is displayed, and resumes
after it has been dismissed.

The alert() method has been used throughout this book. It simply
accepts a string to display to the user. When alert() is called, a
system message box displays the specifi ed text to the user, followed by
a single OK button.

Alert dialogs are typically used when users must be made aware of something that they have no
control over, such as an error. A user’s only choice is to dismiss the dialog after reading the message.
The second type of dialog is invoked by calling confirm(). A confi rm dialog looks similar to an
alert dialog in that it displays a message to the user. The main difference between the two is the

To determine if the user clicked OK or Cancel, the confirm() method
returns a Boolean value: true if OK was clicked, or false if Cancel
was clicked or the dialog box was closed by clicking the X in the
corner. Typical usage of a confi rm dialog looks like this:

if (confirm(“Are you sure?”)) {
alert(“I’m so glad you’re sure! “);
} else {
alert(“I’m sorry to hear you’re not sure. “);
}

If the OK button is clicked, prompt() returns the value in the text box; if Cancel is clicked or the
dialog is otherwise closed without clicking OK, the function returns null. Here’s an example:

var result = prompt(“What is your name? “, “”);
if (result !== null) {
alert(“Welcome, “ + result);
}

JavaScript Variables

Variables store a value you can refer to later in the script. Variable names
can be nearly any valid identifi er. A JavaScript identifi er is a word that
contains only letters, numbers, $, and _, and that doesn’t start with a
number.
Variables are a great demonstration of how statements and expressions
can be combined. You use a variable declaration statement to create a
variable.

var myVariable;

If you already have a variable, you can use a variable assignment expression
to assign it a value.

myVariable = 42;
42
You can combine a variable declaration with an assignment expression.
var myVariable = 42;
You can also string together several variable declarations with commas.
Don’t forget the commas, though! Leaving off a comma can have the
unintended side effect of declaring a global variable when you don’t
mean to do that.var variable1 = 4,
variable2 = 8,
variable3 = 15;

JavaScript has a relatively small number of built-in data types, including
these common types:
var myNumber = 42;
var myString = "A string of text";
var myBoolean = true;
var myArray = [myNumber, myString, myBoolean];

JavaScript Alert

The JavaScript alert is a dialogue box that pops up and takes the focus away from the current window and forces the web browser to read the message.


1.
<form>
<input type="button" onclick=
"alert('Are you sure you want to call')"
value="See">
</form>


2.
function myFunc() {
alert("executing myFunc!");
return true;
}

3.

for (var i = 0; i < 10; i++) {
var link = document.createElement("a");
link.innerHTML = "Link " + i;
link.href = "#";
link.onclick = function() {
alert("This is link " + i);
return false;
};
document.body.appendChild(link);
}

Creating A Function In Javascript

The basic structure of a function looks like this:

function functionName() {
// the JavaScript you want to run
}

The keyword function lets the JavaScript interpreter know you’re creating a function—
it’s similar to how you use if to begin an if/else statement or var to create a variable.

function printToday()
{
var today = new Date();
document.write(today.toDateString());
}

The function’s name is printToday. It has just two lines of JavaScript code that retrieve
the current date, convert the date to a format we can understand

Javascript Do While Loops

There’s another, less common type of loop, known as a do/while loop. This type of
loop works nearly identically to a while loop. Its basic structure looks like this:

do {
// javascript to repeat
} while (condition) ;

do {
var luckyNumber = prompt('What is your lucky number?','');
luckyNumber = parseInt(luckyNumber, 10);
} while (isNaN(luckyNumber));

Save this file and preview it in a web browser. Try typing text and other nonnumeric
symbols in the prompt dialog box. That annoying dialog box continues
to appear until you actually type a number.

Javascript For Loops

JavaScript offers another type of loop, called a for loop, that’s a little more compact
(and a little more confusing). For loops are usually used for repeating a series of
steps a certain number of times, so they often involve some kind of counter variable,
a conditional test, and a way of changing the counter variable. In many cases,
a for loop can achieve the same thing as a while loop, with fewer lines of code. For
example.

for (var num=1; num<=100; num++) {
document.write('Number ' + num + '<br>');
}


var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday','Friday', 'Saturday', 'Sunday'];
for (var i=0; i<days.length; i++) {
document.write(days[i] + ', ');
}

Since for loops provide an easy way to repeat a series of steps a set number of times,
they work really well for working through the elements of an array. The while loop
in Figure 3-5, which writes each item in an array to the page, can be rewritten using
a for loop,

Javascript While Loops

A while loop repeats a chunk of code as long as a particular condition is true; in other
words, while the condition is true. The basic structure of a while loop is this:

while (condition) {
// javascript to repeat
}

The first line introduces the while statement. As with a conditional statement, you
place a condition between the set of parentheses that follow the keyword while.

Say you want to print the numbers 1 to 5 on a page. One possible way to do that is
like this:

document.write('Number 1 <br>');
document.write('Number 2 <br>');
document.write('Number 3 <br>');
document.write('Number 4 <br>');
document.write('Number 5 <br>');

Notice that each line of code is nearly identical—only the number changes from line
to line. In this situation, a loop provides a more efficient way to achieve the same goal:

var num = 1;
while (num <= 5) {
document.write('Number ' + num + '<br>');
num += 1;
}

Javascript Array

You can access the contents of a simple variable just by using the variable’s name.
For example, alert(lastName) opens an alert box with the value stored in the variable
lastName. However, because an array can hold more than one value, you can’t just
use its name alone to access the items it contains. A unique number, called an index,
indicates the position of each item in an array. To access a particular item in an array,
you use that item’s index number. For example, say you’ve created an array with
abbreviations for the days of the week, and want to open an alert box that displayed
the first item.

var days = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'];
alert(days[0]);


Javascript Object Type


Objects are
created by using the new operator followed by the name of the object type to create. Developers
create their own objects by creating instances of the Object type and adding properties and/or
methods to it, as shown here:

var o = new Object();

Each Object instance has the following properties and methods:
constructor — The function that was used to create the object. In the previous example,
the constructor is the Object() function.

hasOwnProperty(propertyName) — Indicates if the given property exists on the object
instance (not on the prototype). The property name must be specifi ed as a string (for
example, o.hasOwnProperty(“name”)).

isPrototypeOf(object) — Determines if the object is a prototype of another object.

propertyIsEnumerable(propertyName) — Indicates if the given property can be
enumerated using the for-in statement (discussed later in this chapter). As with
hasOwnProperty(), the property name must be a string.

toLocaleString() — Returns a string representation of the object that is appropriate for
the locale of execution environment.

toString() — Returns a string representation of the object.

valueOf() — Returns a string, number, or Boolean equivalent of the object. It often
returns the same value as toString().

HTML5 Constraint Validation API

HTML5 introduces the ability for browsers to validate data in forms before submitting to the
server. This capability enables basic validation even when JavaScript is unavailable or fails to load.
The browser itself handles performing the validation based on rules in the code and then displays
appropriate error messages on its own (without needing additional JavaScript). Of course, this
functionality works only in browsers that support this part of HTML5, including Firefox 4+,
Safari 5+, Chrome, and Opera 10+.
Validation is applied to a form fi eld only under certain conditions. You can use HTML markup to
specify constraints on a particular fi eld that will result in the browser automatically performing
form validation.

Required Fields
The fi rst condition is when a form fi eld has a required attribute, as in this example:

<input type=”text” name=”username” required>

Any field marked as required must have a value in order for the form to be submitted. This
attribute applies to <input>, <textarea>, and <select> fi elds (Opera through version 11 doesn’t
support required on <select>). You can check to see if a form fi eld is required in JavaScript by
using the corresponding required property on the element:
var isUsernameRequired = document.forms[0].elements[“username”].required;
You can also test to see if the browser supports the required attribute using this code snippet:
var isRequiredSupported = “required” in document.createElement(“input”);
This code uses simple feature detection to determine if the property required exists on a newly
created <input> element.

Keep in mind that different browsers behave differently when a form fi eld is required. Firefox 4 and
Opera 11 prevent the form from submitting and pop up a help box beneath the fi eld, while Safari (as
of version 5) and Chrome (as of version 9) do nothing and don’t prevent the form from submitting.

Javascript Event Object

Properties

Different types of events have different properties, which you’ll learn
about later in the chapter. Here are a few properties common to all standard
Event objects:
■ type The type of the event, like “click,” “load,” or “keypress.”
■ target The element that originally dispatched the event. This may not
be the same as the element to which the event handler is attached.
■ currentTarget The element to which you attached the event handler.
In most cases, it is synonymous with the this keyword. If you change
the context of the event handler with call() or apply(), you can still
access the element with currentTarget.
■ eventPhase A number that indicates whether the event is currently
capturing (1), bubbling (3), or at the target element (2). Find out more
information in the “Event Bubbling and Capturing” section later in this
chapter.
■ timeStamp A number in seconds that represents the time at which the
event occurred.


<a id="link" href="http://www.google.com">Don't go to
Google</a>
var link = document.getElementById("link");
link.addEventListener("click", dontFollowLink, false);
function dontFollowLink(event) {
alert("Not going to " + this.href);
event.preventDefault();

}


In Internet Explorer, the Event object isn’t available as an argument
of the handler. Instead, it’s a property of window. To write crossbrowser
DOM Level 0 code, look for the Event object in both places.
function handler(event) {
event = event || window.event;
}

Javascript Cookies

Cookies are small strings that let you store data across page views and
sessions. These are some common uses of cookies:
1. Keeping track of whether the user has logged in to your site
2. Remembering that a user has visited a page before
3. Differentiating between fi rst-time visitors and repeat visitors
Cookies are also sent to the server with every page request. That’s how
the server knows whether the user is logged in. Because cookies add data
to the request and therefore increase the size of the request, cookie data
is limited to 4KB.
The window.document object has a funny little property called cookie.
You can use that object to read and set cookie data.
Setting Cookies
To set a cookie, just assign the name and value to document.cookie
in the following format:
document.cookie = "name=value";
You can set only one cookie at a time, but assigning another value to
document.cookie doesn’t overwrite the previous cookies, unless one of
them shares the same name. You can continue to assign name/value pairs
to document.cookie until you hit the 4KB limit enforced by the browser.
// Adding another cookie
document.cookie = "anotherName=anotherValue";
You should always pass the value part of the string through
encodeURIComponent() to make sure it doesn’t contain any illegal
characters such as spaces, commas, and semicolons.
var cookieValue = "encoded value";
document.cookie = "thirdCookie=" +
encodeURIComponent(cookieValue);
You can also set the following optional parameters that affect the



// This secure cookie will last a year
document.cookie = "name=value;max-age=" + (60*60*24*365) +
";secure;";

You’ll have to use your string manipulation skills to extract a single
cookie’s value from this string. Regular expressions come in handy here.

function getCookie(name) {
// Get each individual cookie by splitting
// on semicolons and possible spaces
var cookies = document.cookie.split(/;\s*/);
// Make a regular expression to match the name
// and value in a subpattern
var pattern = new RegExp("\\b" + name + "=(.*)");
// Check each cookie until you fi nd a match
for (var i = 0, l = cookies.length; i < l; i++) {
var match = cookies[i].match(pattern);
if (match) {
return decodeURIComponent(match[1]);
}
}
}

Javascript forEach

Looping over arrays using functions is increasingly common, especially in
certain libraries. Modern browsers support the forEach() method, but
you can also build your own.
function arrayForEach(array, loopFunc) {
// If the browser support forEach, use it because
// it will be faster
if ("forEach" in array) {
return array.forEach(loopFunc);

// Otherwise, loop over the array and pass in
// the array values to the loop function
} else {
for (var i = 0, l = array.length; i < l; i++) {
loopFunc(array[i], i, array);
}
return array;
}
}
function doSomeMath(num) {
console.log(num * 10 - 5);
}
arrayForEach([1,2,3], doSomeMath);



5
15
25

Javascript Creating Arrays

The best way to create a new array is with the array literal syntax ([]),
but the array constructor function is available too. If you pass a single
number value to the constructor function, you get an array fi lled with
that many undefi ned values.
var myArray = [];
var myFilledArray = new Array(4);
myFilledArray;
[undefi ned, undefi ned, undefi ned, undefi ned]
Properties
Like strings, arrays have one built-in property: length. This property is
equal to the number greater than the last index in the array. This is true
even if you skip some indices.
["a", 1, true, null].length;
4
var myArray = [];
myArray.length;
0
myArray[99] = 1;
1
myArray.length;
100
The new length of myArray is 100 even though it contains only one value
at index 99. All the other values are undefined.

JavaScript String Length

The length  returns the number of characters that are in a string, using
an integer.


<script type="text/javascript">
var testString = "11111";
var length = testString.length;
document.write("The string length is: " + length);

</script>



output:-

The string length is: 5

Comparing strings in JavaScript


<script type="text/javascript">
var username = "test";
if(username == "test")
    document.write("Welcome");
else
    document.write("Access Denied!");
document.write("<br /><br />Try again?<br /><br />");


</script>

While '14' == 14 is true (because by converting either the left side
value to a number or converting the right side value to a text string
will result in both being the same) '123' === 123 is false since one
value is a text string and the other is a number.

The === operator does the same thing with one minor difference. This
operator does not convert data from one type to another.

JavaScript String indexOf

var p = navigator.platform;
system.win = p.indexOf(“Win”) == 0;
system.mac = p.indexOf(“Mac”) == 0;
system.x11 = (p.indexOf(“X11”) == 0) || (p.indexOf(“Linux”) == 0);


This code uses the indexOf() method to look at the beginning of the platform string. To detect
Windows, the platform-detection code simply looks for the string “Win” at the beginning of the
platform string (covers both “Win32” and “Win64”). Testing for a Mac platform is done in the same
way to accommodate both “MacPPC” and “MacIntel”. The test for Unix looks for both “X11” and
“Linux” at the beginning of the platform string to future-proof this code against other variants.

<script type="text/javascript">
var mURL = "http://www.google.com/";
var mPosition = mURL.indexOf("www");

document.write("The position of www  =  " + mPosition); 
</script>