Ce diaporama a bien été signalé.
Nous utilisons votre profil LinkedIn et vos données d’activité pour vous proposer des publicités personnalisées et pertinentes. Vous pouvez changer vos préférences de publicités à tout moment.

CSS Unit II - Array, Function and String

126 vues

Publié le

Course Title - Client Side Scripting Language (JavaScript)
Couse Code - 22519
Unit II - Array, Function and String

Publié dans : Ingénierie
  • Soyez le premier à commenter

  • Soyez le premier à aimer ceci

CSS Unit II - Array, Function and String

  1. 1. Array, Function and String Prepared By Prof. Rahul S. Tamkhane Unit - II Subject - Client Side Scripting Language (CSS-22519)
  2. 2. Compiled By - Prof. Rahul S. Tamkhane Unit Outcomes (UOs) 2a. Create array to solve the given problem. 2b. Perform the specified string manipulation operation on the given String(s). 2c. Develop JavaScript to implement the given function. 2d. Develop JavaScript to convert the given Unicode to character form. 2e. Develop JavaScript to convert the given character to Unicode and vice-versa. Unit II - Array, Function and String (14 Marks) 2 Course Outcome (CO) - Implement Arrays and Functions in JavaScript
  3. 3. Compiled By - Prof. Rahul S. Tamkhane Contents ■ Array – declaring an Array, Initializing an Array, defining an Array elements, Looping an Array, Adding an Array element, sorting an Array element, Combining an Array elements into a String, changing elements of an Array, Objects as associative Arrays ■ Function – defining a function, writing a function, adding an arguments, scope of variable and arguments ■ Calling a function – calling a function with or without an argument, calling function from HTML, function calling another function, Returning a value from a function ■ String – manipulation a string, joining a string, retrieving a character from given position, retrieving a position of character in a string, dividing text, copying a sub string, converting string to number and numbers to string, finding a Unicode of a character-charCodeAt(), fromCharCode(). Unit II - Array, Function and String (14 Marks) 3
  4. 4. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array ■ What Is an Array? ■ If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: var car1 = “Audi"; var car2 = " BMW"; var car3 = " Volvo"; ■ An array is a special type of variable, which can hold more than one value at a time. ■ An array can hold many values under a single name, and you can access the values by referring to an index number. Unit II - Array, Function and String (14 Marks) 4
  5. 5. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Declaring an array (Contd.) ■ JavaScript arrays are used to store multiple values in a single variable. ■ There are 2 ways to construct array in JavaScript 1) By array literal 2) By using an Array constructor (using new keyword) Unit II - Array, Function and String (14 Marks) 5
  6. 6. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Declaring an array (Contd.) 1) By array literal ■ Using an array literal is the easiest way to create a JavaScript Array. ■ Syntax: var array_name = [item1, item2, ...]; ■ Example: var fruits = ["Apple", "Orange", "Plum"]; ■ A declaration can span multiple lines: var fruits = [ "Apple", "Orange", "Plum“ ]; Unit II - Array, Function and String (14 Marks) 6
  7. 7. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Declaring an array (Contd.) 1) By array literal Unit II - Array, Function and String (14 Marks) 7
  8. 8. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Declaring an array (Contd.) 2) By using an Array constructor (using new keyword) ■ You can also create an array using Array constructor with new keyword ■ This declaration has five parts: 1) var keyword 2) Array name 3) Assignment operator 4) new operator 5) Array ( ) constructor ■ Syntax: var array_name = new Array(); Unit II - Array, Function and String (14 Marks) 8
  9. 9. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Declaring an array 2) By using an Array constructor (using new keyword) Unit II - Array, Function and String (14 Marks) 9
  10. 10. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Initializing an Array (Contd.) ■ Initialization is the process of assigning a value to a variable or an array ■ An array in JavaScript can be defined and initialized in two ways, – Array literal – Array constructor syntax. Unit II - Array, Function and String (14 Marks) 10
  11. 11. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Initializing an Array (Contd.) Using Array literal ■ It takes a list of values separated by a comma and enclosed in square brackets. ■ Syntax: var <array-name> = [element0, element1, element2,... elementN]; ■ Examples: var stringArray = ["one", "two", "three"]; var numericArray = [1, 2, 3, 4]; var decimalArray = [1.1, 1.2, 1.3]; var booleanArray = [true, false, false, true]; var mixedArray = [1, "two", "three", 4]; Unit II - Array, Function and String (14 Marks) 11
  12. 12. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Initializing an Array (Contd.) Using Array Constructor ■ You can initialize an array with Array constructor syntax using new keyword. ■ The Array constructor has following three forms. ■ Syntax: var arrayName = new Array(); var arrayName = new Array(Number length); var arrayName = new Array(element1, element2, element3,... elementN); Unit II - Array, Function and String (14 Marks) 12
  13. 13. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Initializing an Array Using Array Constructor ■ Examples: var stringArray = new Array(); stringArray[0] = "one"; stringArray[1] = "two"; stringArray[2] = "three"; stringArray[3] = "four"; var numericArray = new Array(3); numericArray[0] = 1; numericArray[1] = 2; numericArray[2] = 3; var mixedArray = new Array(1, "two", 3, "four"); Unit II - Array, Function and String (14 Marks) 13
  14. 14. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Defining an Array elements ■ An array is a list of things of same king like list of students, list of products, list of customer names, etc. ■ Each item in array is identified by index of an array. ■ The first item‟s index is 0, second item‟s is 1, and so on. ■ We can define array elements after declaration using index in square brackets ■ For example var fruits = new Array(3); // Array of size 3 fruits[0] = “Orange”; // fruits[0] holds “Orange” fruits[1] = “Apple”; // fruits[1] holds “Apple” fruits[2] = “Kiwi”; // fruits[2] holds “Kiwi” Unit II - Array, Function and String (14 Marks) 14
  15. 15. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Looping an Array (Contd.) ■ Let us consider we want to display all the elements of array, for this we can use the for loop to access each array element. ■ For example ■ The document.write() method of document object displays the array elements on the document. Unit II - Array, Function and String (14 Marks) 15
  16. 16. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Adding an Array element (Contd.) ■ In some situation there is need to increase the size of the array. This can be done by using two ways. 1) Using push method of array arrObject.push(elem1, elem2, …, elemn) 2) Using length property of array arrObject [ arrObject.length] = element; Unit II - Array, Function and String (14 Marks) 16
  17. 17. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Adding an Array element push( ) Method ■ The push() method adds new items to the end of an array, and returns the new length. ■ The new item(s) will be added at the end of the array. ■ This method changes the length of the array. ■ Syntax array.push(item1, item2, ..., itemX) ■ Examples Unit II - Array, Function and String (14 Marks) 17
  18. 18. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Adding an Array element unshift( ) Method ■ The unshift() method adds new items to the beginning of an array, and returns the new length. ■ This method changes the length of an array. ■ Syntax array.unshift(item1, item2, ..., itemX) ■ Examples Unit II - Array, Function and String (14 Marks) 18
  19. 19. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Sorting an Array element (Contd.) ■ Sometimes we want values in sorted order, string alphabetically and numbers in ascending order. ■ The sort () method reorders values assigned to elements of an array. – Declare array – Assign values to elements of an array – Call the sort() method ■ Syntax array.sort() ■ Examples var cars = new Array("Audi", "Volvo", "BMW", "Tavera"); cars.sort(); Unit II - Array, Function and String (14 Marks) 19
  20. 20. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Sorting an Array element Unit II - Array, Function and String (14 Marks) 20
  21. 21. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Combining an Array elements into a string (Contd.) ■ Sometimes we want to combine values of an array element into one string. ■ For example, an array var arr = new Array(3); arr[0] = “PHP”; arr[1] = “JavaScript”; arr[2] = “JSP”; ■ By combining, we will get the string PHP, JavaScript, JSP ■ Array elements can be combined in two ways: 1) Using concat() method 2) Using join() method Unit II - Array, Function and String (14 Marks) 21
  22. 22. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Combining an Array elements into a string concat( ) Method (Contd.) 1) Using concat() method ■ The array concat() method is used to merge two or more arrays together. ■ This method does not alter the original arrays passed as arguments. ■ Syntax: var new_array = arrObj.concat(value1[, value2[, ...[, valueN]]]) Unit II - Array, Function and String (14 Marks) 22
  23. 23. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Combining an Array elements into a string concat( ) Method (Contd.) Unit II - Array, Function and String (14 Marks) 23 Example Output var num1 = [11, 12, 13], num2 = [14, 15, 16], num3 = [17, 18, 19]; print(num1.concat(num2, num3)); [11,12,13,14,15,16,17,18,19] var alpha = ['a', 'b', 'c']; print(alpha.concat(1, [2, 3])); [a,b,c,1,2,3] var num1 = [[23]]; var num2 = [89, [67]]; print(num1.concat(num2)); [23,89,67]
  24. 24. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Combining an Array elements into a string concat( ) Method Unit II - Array, Function and String (14 Marks) 24
  25. 25. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Combining an Array elements into a string join( ) Method (Contd.) 2) Using join() method ■ The array join() function is used to join the elements of the array together into a string. ■ A string to separate each elements of the array. If leave it by default array element separate by comma( , ). ■ Syntax: Array.join([separator]) Unit II - Array, Function and String (14 Marks) 25
  26. 26. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Combining an Array elements into a string join( ) Method (Contd.) Unit II - Array, Function and String (14 Marks) 26 Example Output var a = [1, 2, 3, 4, 5, 6]; print(a.join('|')); 1|2|3|4|5|6 var a = [1, 2, 3, 4, 5, 6]; print(a.join()); 1, 2, 3, 4, 5, 6 var a = [1, 2, 3, 4, 5, 6]; print(a.join('')); 123456
  27. 27. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Combining an Array elements into a string join( ) Method Unit II - Array, Function and String (14 Marks) 27
  28. 28. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Changing elements of an Array shift( ) Method ■ An array can be used to implement a to-do list. ■ In that elements are added at end and it come out once the task is completed. ■ The shift() method removes the first item (element) of an array. ■ This method changes the length of the array. ■ The return value of the shift method is the removed item. ■ Note: This method will change the original array. ■ Syntax array.shift( ) ■ Examples Unit II - Array, Function and String (14 Marks) 28
  29. 29. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Changing elements of an Array pop( ) Method ■ The pop() method removes the last element of an array, and returns that element. ■ This method changes the length of an array. ■ Syntax array.pop( ) ■ Examples Unit II - Array, Function and String (14 Marks) 29
  30. 30. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Objects as an Associative Array (Contd.) ■ The dot (.) operator is used to access the properties of an object. ■ We can also used that to access the properties of an array. object.property object [“property”] ■ This is popular with associative array. ■ An associative array is an array of key:value pairs where keys acts as index to get any value. Unit II - Array, Function and String (14 Marks) 30
  31. 31. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Objects as an Associative Array (Contd.) ■ To create an associative array used object literal as follow: var arr = {“one”: 1, “Two”: 2, “Three”: 3}; var y = arr[“one”]; ■ We can then use the for…in loop to display all elements. for( var key in arr) { document.write(arr[key] + “<br>”); } Unit II - Array, Function and String (14 Marks) 31
  32. 32. Compiled By - Prof. Rahul S. Tamkhane 2.1 Array – Objects as an Associative Array Unit II - Array, Function and String (14 Marks) 32
  33. 33. Compiled By - Prof. Rahul S. Tamkhane 2.2 Functions ■ A function is block of code designed to perform a particular task. ■ It is reusable code which can be called anywhere in program. ■ There are two types of functions: 1) Built-in functions 2) User-defined functions Unit II - Array, Function and String (14 Marks) 33
  34. 34. Compiled By - Prof. Rahul S. Tamkhane 2.2 Functions – Defining a function (Contd.) ■ A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). ■ Function names can contain letters, digits, underscores, and dollar signs (same rules as variables). ■ The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...) ■ The code to be executed, by the function, is placed inside curly brackets: { } ■ It is recommended that the function should define in <head> tag. Unit II - Array, Function and String (14 Marks) 34
  35. 35. Compiled By - Prof. Rahul S. Tamkhane 2.2 Functions – Defining a function ■ A function definition consists of four parts: 1) Function name 2) Parenthesis 3) Code block 4) Return statement (Optional) Unit II - Array, Function and String (14 Marks) 35
  36. 36. Compiled By - Prof. Rahul S. Tamkhane 2.2 Functions – Writing a function (Contd.) ■ In JavaScript a function can be written with argument or winthout argument. ■ Syntax function functionName([arg1, arg2, ...argN]) { // code to be executed } ■ Example Unit II - Array, Function and String (14 Marks) 36 function sayHello() { alert("Hello there"); }
  37. 37. Compiled By - Prof. Rahul S. Tamkhane 2.2 Functions – Writing a function (Contd.) Unit II - Array, Function and String (14 Marks) 37
  38. 38. Compiled By - Prof. Rahul S. Tamkhane 2.2 Functions – Adding an arguments (Contd.) ■ A JavaScript a function can also take parameters (arguments). ■ The arguments must be unique and separated by comma. ■ Syntax function functionName([arg1, arg2, ...argN]) { // code to be executed } ■ Example Unit II - Array, Function and String (14 Marks) 38 function cube(a) { document.write(a*a*a); }
  39. 39. Compiled By - Prof. Rahul S. Tamkhane 2.2 Functions – Adding an arguments (Contd.) Unit II - Array, Function and String (14 Marks) 39 Program to create a function Square, calculate square of a number and display it.
  40. 40. Compiled By - Prof. Rahul S. Tamkhane 2.2 Functions – Adding an arguments (Contd.) Unit II - Array, Function and String (14 Marks) 40
  41. 41. Compiled By - Prof. Rahul S. Tamkhane 2.2 Functions – Scope of variable and arguments (Contd.) ■ The scope of variable refers to the visibility of variables. ■ Two types of scopes in JavaScript: 1) Local scope 2) Global scope Unit II - Array, Function and String (14 Marks) 41
  42. 42. Compiled By - Prof. Rahul S. Tamkhane 2.2 Functions – Scope of variable and arguments (Contd.) 1) Local scope  Variables declared within a JavaScript function, become LOCAL to the function.  Local variables can only be accessed from within the function.  Local variables are created when a function starts, and deleted when the function is completed.  Example Unit II - Array, Function and String (14 Marks) 42 function showMessage() { var message = “Hello, I’m JavaScript!”; // local variable alert( message ); } showMessage(); // Hello, I'm JavaScript! alert( message ); // <-- Error! The variable is local to the function
  43. 43. Compiled By - Prof. Rahul S. Tamkhane 2.2 Functions – Scope of variable and arguments (Contd.) 2) Global scope  Variables declared outside of any function, becomes GLOBAL .  Local variables can only be accessed from within the function.  Global variables are visible from any function.  Example Unit II - Array, Function and String (14 Marks) 43 var userName = 'John'; function showMessage() { var userName = "Bob"; // declare a local variable var message = 'Hello, ' + userName; // Bob alert(message); } // the function will create and use its own userName showMessage(); alert(userName); //John, unchanged, the function did not access the outer variable
  44. 44. Compiled By - Prof. Rahul S. Tamkhane 2.3 Calling a Function ■ We can call a function by using the function name separated by the value of parameters enclosed between parenthesis and a semicolon at the end. ■ The values must be placed in the same order that the arguments are listed in the function definition ■ Syntax functionName( Value1, Value2, ..); ■ Example square(23); Unit II - Array, Function and String (14 Marks) 44
  45. 45. Compiled By - Prof. Rahul S. Tamkhane 2.3 Calling a Function (Contd.) Unit II - Array, Function and String (14 Marks) 45 <script type = "text/javascript"> // Function definition function welcomeMsg(name) { document.write("Hello " + name + " welcome to RCPP"); } // creating a variable var nameVal = “Rohan"; // calling the function welcomeMsg(nameVal); </script> Output Hello Rohan welcome to RCPP
  46. 46. Compiled By - Prof. Rahul S. Tamkhane 2.3 Calling a Function - Without an argument (Contd.) ■ To invoke a function somewhere later in the script, simply write the name of that function followed by parenthesis. ■ To call a function which doesn‟t takes any arguments is simple just write the function name and empty brackets. ■ Syntax functionName(); Unit II - Array, Function and String (14 Marks) 46
  47. 47. Compiled By - Prof. Rahul S. Tamkhane Unit II - Array, Function and String (14 Marks) 47 <!-- Write a program to find Factorial of a number --> <html> <head> <title>Find Factorial of a number</title> <script> // function declaration function fact() { var num = document.getElementById("input").value; var f = 1; for(i = num; i > 0; i--) { f = f * i; } document.getElementById("panel").innerHTML = "<h2>Factorial of given no. is " + f + "<br>"; } </script> </head> <body> Enter the number <br><br> <input id="input" type="text" value="0"><br> <input type="button" value="Find Factorial" onclick="fact()"><br> <p id="panel"></p> </body> </html>
  48. 48. Compiled By - Prof. Rahul S. Tamkhane 2.3 Calling a Function - With argument (Contd.) ■ We can call function by passing arguments. ■ A function can take arguments which are separated by comma. ■ To call this type of function we have to pass arguments in order they are defined in a function definition. ■ Syntax (Function definition) function functionName(arg1, arg2, ...argN) { // code to be executed } ■ Syntax (Function call) functionName(arg1, arg2, ...argN); Unit II - Array, Function and String (14 Marks) 48
  49. 49. Compiled By - Prof. Rahul S. Tamkhane Unit II - Array, Function and String (14 Marks) 49 <!-- Write a program to input number from user and check whether it is EVEN or ODD number --> <html> <head> <title>Check whether no. is EVEN or ODD</title> <script> // function declaration function isEven(num) { if(num % 2 == 0) { document.write("<h2>Number is EVEN</h2>"); } else { document.write("<h2>Number is ODD</h2>"); } } </script> </head> <body> <script> var num = Number(prompt("Enter the number", "0")); isEven(num); </script> </body> </html>
  50. 50. Compiled By - Prof. Rahul S. Tamkhane 2.3 Calling a Function – Calling function from HTML (Contd.) ■ We can call JavaScript function from HTML code of webpage. ■ Basically, it is called in response to an event, such as – when the page is loaded or unloaded by the browser ■ To call the function from HTML, just make a function call from HTML tag attribute ■ Let us consider, we have to call a function WelcomeMessage() when the webpage loads then we can call it from <body> tag as below: <body onload = “WelcomeMessage()”> Unit II - Array, Function and String (14 Marks) 50
  51. 51. Compiled By - Prof. Rahul S. Tamkhane Unit II - Array, Function and String (14 Marks) 51 <!– Program to call a function from HTML --> <html> <head> <script type="text/javascript"> function functionOne() { alert('You clicked the top text'); } function functionTwo() { alert('You clicked the bottom text'); } </script> </head> <body> <p><a href="#" onClick="functionOne();">Top Text</a></p> <p><a href="javascript:functionTwo();">Bottom Text</a></p> </body> </html>
  52. 52. Compiled By - Prof. Rahul S. Tamkhane 2.3 Calling a Function – Function calling another function (Contd.) ■ Developers may divide an application into many functions, each of which handles a portion of the application. ■ We can call one function from another function. ■ For example, we want to validate user login on the basis of username and password entered by user, then we will create two methods logon() and validateUser() in program and call second method in first method. Unit II - Array, Function and String (14 Marks) 52
  53. 53. Compiled By - Prof. Rahul S. Tamkhane Unit II - Array, Function and String (14 Marks) 53 <!– Program to demonstrate calling one function from another function --> <html> <head> <title>Change background color of webpage</title> <script> function logon() { var username = prompt("Enter username"); var password = prompt("Enter password"); var isValid = validateUser(username, password); if(isValid) { alert("Valid Login"); } else { alert("Invalid Login"); } } function validateUser(uname, pwd) { if(uname == "admin" && pwd == "123") return true; else return false; } </script> </head> <body onload="logon()"> </body> </html>
  54. 54. Compiled By - Prof. Rahul S. Tamkhane 2.3 Calling a Function – Returning a value from a function (Contd.) ■ There are some situations when we want to return some values from a function after performing some operations. ■ In such cases, we can make use of the return statement in JavaScript. ■ A JavaScript function can have an optional return statement. ■ It should be the last statement in a function. ■ The return value is "returned" back to the "caller“. ■ Syntax function functionName([arg1, arg2, ...argN]) { // code to be executed return value; } Unit II - Array, Function and String (14 Marks) 54
  55. 55. Compiled By - Prof. Rahul S. Tamkhane 2.3 Calling a Function – Returning a value from a function (Contd.) Unit II - Array, Function and String (14 Marks) 55 2 1
  56. 56. Compiled By - Prof. Rahul S. Tamkhane Unit II - Array, Function and String (14 Marks) 56 <!–- Program to return a value from function--> <html> <head> <title>Check age of user</title> <script> function checkAge(age) { if (age >= 18) { return true; } else { return confirm('Do you have permission from your parents?'); } } let age = prompt('How old are you?', 18); if (checkAge(age)) { alert('Access granted'); } else { alert('Access denied'); } </script> </head> <body> </body> </html>
  57. 57. Compiled By - Prof. Rahul S. Tamkhane Unit II - Array, Function and String (14 Marks) 57 <!– Program to calculate area of a rectangle using function --> <html> <head> <title>Calculate area of Rectangle</title> <script> var length = 23; var breadth = 11; document.write("Area of Rectangle = " + areaRect(length, breadth)); function areaRect(l, b) { return l*b; } </script> </head> <body> </body> </html>
  58. 58. Compiled By - Prof. Rahul S. Tamkhane 2.4 String (Contd.) ■ Strings are used to storing and manipulating text. ■ In JavaScript, the textual data is stored as strings. ■ There is no separate type for a single character. ■ Strings can be enclosed within either single quotes, double quotes or backticks. Unit II - Array, Function and String (14 Marks) 58 var single = 'single-quoted'; var double = "double-quoted"; let backticks = `backticks`;
  59. 59. Compiled By - Prof. Rahul S. Tamkhane 2.4 String (Contd.) ■ Single and double quotes are essentially the same. ■ Backticks, however, allow us to embed any expression into the string, by wrapping it in ${…} Unit II - Array, Function and String (14 Marks) 59 function sum(a, b) { return a + b; } alert(`1 + 2 = ${sum(1, 2)}.`); // 1 + 2 = 3.
  60. 60. Compiled By - Prof. Rahul S. Tamkhane 2.4 String (Contd.) 1) By string literal ■ The string literal is created using double quotes. ■ Syntax var stringName = “value”; ■ Example var color = “cyan”; ■ This method references internal pool of string objects. If there already exists a string value “cyan”, then color will reference of that string and no new String object will be created. Unit II - Array, Function and String (14 Marks) 60
  61. 61. Compiled By - Prof. Rahul S. Tamkhane 2.4 String (Contd.) 2) By string object (using new keyword) ■ You can create string using new keyword. ■ Syntax var stringname=new String("string literal"); ■ Example var color = new String(“cyan”); ■ Difference between using string literal and string object Unit II - Array, Function and String (14 Marks) 61
  62. 62. Compiled By - Prof. Rahul S. Tamkhane Unit II - Array, Function and String (14 Marks) 62 <!-- Program to create a string using String literal and String object --> <html> <head> <title>Strings demo</title> </head> <body> <script> var text1 = "Hello JavaScript"; // Using String literal var text2 = new String("Functions"); // Using String object document.write(text1 + "<br>"); document.write(text2 + "<br>"); document.write("<br>Type of text1 is " + typeof(text1)); document.write("<br>Type of text2 is " + typeof(text2)); </script> </body> </html>
  63. 63. Compiled By - Prof. Rahul S. Tamkhane 2.4 String – Manipulating a string (Contd.) ■ String are objects within JavaScript language. ■ They are not stored as character array, so built-in functions must be used to manipulate their values. ■ These functions provide access to the contents of a string variables. ■ JavaScript String object has various properties and methods ■ String Properties 1) Constructor - Returns a reference to the String function that created the object. 2) Length - Returns the length of the string. 3) Prototype - The prototype property allows you to add properties and methods to an object. Unit II - Array, Function and String (14 Marks) 63
  64. 64. Compiled By - Prof. Rahul S. Tamkhane Unit II - Array, Function and String (14 Marks) 64 <!-- Program to demonstrate use of prototype and constructor property of String object --> <html> <head> <title>User-defined objects</title> <script type = "text/javascript"> function book(title, author) { this.title = title; this.author = author; } </script> </head> <body> <script type = "text/javascript"> var myBook = new book("Perl", "Mohtashim"); book.prototype.price = null; myBook.price = 100; document.write(book.constructor + "<br>"); document.write("Book title is : " + myBook.title + "<br>"); document.write("Book author is : " + myBook.author + "<br>"); document.write("Book price is : " + myBook.price + "<br>"); </script> </body> </body> </html>
  65. 65. Compiled By - Prof. Rahul S. Tamkhane 2.4 String – Manipulating a string (Contd.) ■ All string methods return a new value. They do not change the original variable. Unit II - Array, Function and String (14 Marks) 65 Methods Description charAt() It provides the char value present at the specified index. charCodeAt() It provides the Unicode value of a character present at the specified index. concat() It provides a combination of two or more strings. indexOf() It provides the position of a char value present in the given string. lastIndexOf() It provides the position of a char value present in the given string by searching a character from the last position. search() It searches a specified regular expression in a given string and returns its position if a match occurs. match() It searches a specified regular expression in a given string and returns that regular expression if a match occurs. replace() It replaces a given string with the specified replacement.
  66. 66. Compiled By - Prof. Rahul S. Tamkhane 2.4 String – Manipulating a string Unit II - Array, Function and String (14 Marks) 66 Methods Description substr() It is used to fetch the part of the given string on the basis of the specified starting position and length. substring() It is used to fetch the part of the given string on the basis of the specified index. slice() It is used to fetch the part of the given string. It allows us to assign positive as well negative index. toLowerCase() It converts the given string into lowercase letter. toLocaleLowerCase() It converts the given string into lowercase letter on the basis of host?s current locale. toUpperCase() It converts the given string into uppercase letter. toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host?s current locale. toString() It provides a string representing the particular object. valueOf() It provides the primitive value of string object. split() It splits a string into substring array, then returns that newly created array. trim() It trims the white space from the left and right side of the string.
  67. 67. Compiled By - Prof. Rahul S. Tamkhane 2.4 String – Joining a string (Contd.) ■ When we want to concatenate two string into a single one then that is called as joining a string. ■ Two ways to join strings 1) Using concatenation operator (+) 2) Using concat() method of string object Unit II - Array, Function and String (14 Marks) 67
  68. 68. Compiled By - Prof. Rahul S. Tamkhane 2.4 String – Joining a string (Contd.) 1) Using concatenation operator (+) – You can concatenate two strings using plus (+) operator – Just you have to put plus sign in two string objects that you have declared. – Syntax string1 + string2; – Example var one = “Hello”, two=“World!”; var value = one + two; Unit II - Array, Function and String (14 Marks) 68
  69. 69. Compiled By - Prof. Rahul S. Tamkhane 2.4 String – Joining a string (Contd.) 2) Using concat() method of string object – concat() is a string method that is used to concatenate strings together. – This method appends one or more string values to the calling string and then returns the concatenated result as a new string. – Syntax string.concat(value1, value2, ... value_n); – Example var str = 'It'; var value = str.concat(' is',' a',' great',' day.'); Unit II - Array, Function and String (14 Marks) 69
  70. 70. Compiled By - Prof. Rahul S. Tamkhane Unit II - Array, Function and String (14 Marks) 70 <!-- Program to get first and last name from user and display its Fullname --> <html> <head> <title>Display Fullname of user</title> </head> <body> <script> var fname = prompt("Enter the first name"); var lname = prompt("Enter the lastname"); document.write("HELLO, " + fname.concat(" ", lname)); </script> </body> </html>
  71. 71. Compiled By - Prof. Rahul S. Tamkhane 2.4 String – Retrieving a character from given position (Contd.) ■ A string is an array of characters. ■ Each element in a string can be identified by its index ■ Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character in a string, called stringName, is stringName.length – 1. ■ The charAt() is a method that returns the character from the specified index. ■ The index value can't be a negative, greater than or equal to the length of the string. ■ Syntax: Unit II - Array, Function and String (14 Marks) 71 string.charAt(index);
  72. 72. Compiled By - Prof. Rahul S. Tamkhane Unit II - Array, Function and String (14 Marks) 72 <!-- Program to demonstrate use of charAt( ) method --> <html> <head> <title>Retrieving a character from given position</title> </head> <body> <script> var str = "JavaScript is an object oriented scripting language."; document.write(str + "<br>"); document.write("<br>str.charAt(2) is: " + str.charAt(2)); document.write("<br> str.charAt(8) is: " + str.charAt(8)); </script> </body> </html>
  73. 73. Compiled By - Prof. Rahul S. Tamkhane 2.4 String – Retrieving a position of character in a string ■ It is possible to retrieve a position of character in a string ■ JavaScript provides two methods to find the character(s) in string 1) indexOf() 2) ssearch() Unit II - Array, Function and String (14 Marks) 73
  74. 74. Compiled By - Prof. Rahul S. Tamkhane 2.4 String – Copying a sub string (Contd.) ■ We can also copy one string into a new string. ■ In order to extract a small portion from a string, JavaScript provides three methods 1) substr() 2) substring() 3) slice() Unit II - Array, Function and String (14 Marks) 74
  75. 75. Compiled By - Prof. Rahul S. Tamkhane 2.4 String – Copying a sub string (Contd.) 1) substr() ■ This method extracts parts of a string, beginning at the character at the specified position, and returns the specified number of characters. ■ To extract characters from the end of the string, use a negative start number. ■ This method does not change the original string. ■ Syntax: ■ Note: – If start is positive and >= to the length of the string, it returns an empty string. – If start is negative, it takes character index from the end of the string. – If start is negative or larger than the length of the string, start is set to 0 Unit II - Array, Function and String (14 Marks) 75 string.substr(start, [length])
  76. 76. Compiled By - Prof. Rahul S. Tamkhane Unit II - Array, Function and String (14 Marks) 76 <!-- Program to demonstrate substr() method--> <html> <head> <title>String substr() method demos</title> </head> <body> <script> var str = "Copying a sub string"; // string.substr(start, [length]) document.write("<h2>" + str + "</h2>"); document.write("<br>substr(2) : "+ str.substr(2)); document.write("<br>substr(2, 5) : "+ str.substr(2, 5)); document.write("<br>substr(-4) : "+ str.substr(-4)); document.write("<br>substr(-2, 1) : "+ str.substr(-2, 1)); </script> </body> </html>
  77. 77. Compiled By - Prof. Rahul S. Tamkhane 2.4 String – Copying a sub string (Contd.) 2) substring() ■ This method extracts the characters from a string, between two specified indices, and returns the new sub string. ■ This method extracts the characters in a string between "start" and "end", not including "end" itself. ■ If "start" is greater than "end", this method will swap the two arguments ■ If either "start" or "end" is less than 0, it is treated as 0. ■ This method does not change the original string. ■ Syntax: Unit II - Array, Function and String (14 Marks) 77 string.substring(start, [end])
  78. 78. Compiled By - Prof. Rahul S. Tamkhane Unit II - Array, Function and String (14 Marks) 78 <!-- Program to demonstrate substring() method--> <html> <head> <title>String substring() method demo</title> </head> <body> <script> var str = "Copying a sub string"; // string.substr(start, [end]) document.write("<h2>" + str + "</h2>"); document.write("<br>substring(2) : "+ str.substring(2)); // document.write("<br>substr(1, 6) : "+ str.substr(1, 6)); document.write("<br>substring(1, 6) : "+ str.substring(1, 6)); document.write("<br>substring(6, 1) : "+ str.substring(6, 1)); document.write("<br>substring(-2) : "+ str.substring(-2)); document.write("<br>First character - substring(0, 1) : "+ str.substring(0, 1)); document.write("<br>Last character - substring(str.length-1, str.length) : " + str.substring(str.length-1, str.length)); </script> </body> </html>
  79. 79. Compiled By - Prof. Rahul S. Tamkhane 2.4 String – Copying a sub string (Contd.) 3) slice() ■ This method extracts parts of a string and returns the extracted parts in a new string. ■ Use a negative number to select from the end of the string. ■ Syntax: Unit II - Array, Function and String (14 Marks) 79 string.slice(start, [end])
  80. 80. Compiled By - Prof. Rahul S. Tamkhane Unit II - Array, Function and String (14 Marks) 80 <!-- Program to demonstrate slice() method--> <html> <head> <title>String slice() method demo</title> </head> <body> <script> var str = "Copying a sub string"; // string.slice(start, [end]) document.write("<h2>" + str + "</h2>"); // document.write("<br>substr(2) : "+ str.substr(2)); document.write("<br>slice(2) : "+ str.slice(2)); document.write("<br>slice(2, 9) : "+ str.slice(2, 9)); document.write("<br>slice(-2) : "+ str.slice(-2)); </script> </body> </html>
  81. 81. Compiled By - Prof. Rahul S. Tamkhane 2.4 String – Converting string to number (Contd.) ■ In JavaScript 82 and „64‟ both are different. First is number and second is string containing a number. ■ If we use concatenation (+) operator to add these numbers we will get 8264 ■ JavaScript provides three different ways to convert a string into a number 1) parseInt() 2) parseFloat() 3) Number() Unit II - Array, Function and String (14 Marks) 81
  82. 82. Compiled By - Prof. Rahul S. Tamkhane 2.4 String – Converting string to number (Contd.) parseInt() – The parseInt() method converts a string into an integer (a whole number). – It accepts two arguments. The first argument is the string to convert. The second argument is called the radix. This is the base number used in mathematical systems. For our use, it should always be 10. Unit II - Array, Function and String (14 Marks) 82 Syntax - parseInt(string, [radix]) Example - var text = '42px'; var integer = parseInt(text, 10); // returns 42
  83. 83. Compiled By - Prof. Rahul S. Tamkhane 2.4 String – Converting string to number (Contd.) parseFloat() – The parseFloat() method converts a string into a point number (a number with decimal points). – It parses a string and returns a floating point number – You can even pass in strings with random text in them. Unit II - Array, Function and String (14 Marks) 83 Syntax - parseFloat(string) Example - var text = '3.14someRandomStuff'; var pointNum = parseFloat(text); // returns 3.14
  84. 84. Compiled By - Prof. Rahul S. Tamkhane 2.4 String – Converting string to number (Contd.) Number() ■ The Number() function converts the object argument to a number that represents the object's value. ■ If the value cannot be converted to a legal number, NaN is returned. ■ If the parameter is a Date object, the Number() function returns the number of milliseconds since midnight January 1, 1970 UTC. Unit II - Array, Function and String (14 Marks) 84 Syntax - Number(object) Example - Number('123'); // returns 123 Number('12.3'); // returns 12.3 Number('3.14someRandomStuff'); // returns NaN Number('42px'); // returns NaN
  85. 85. Compiled By - Prof. Rahul S. Tamkhane Unit II - Array, Function and String (14 Marks) 85 <!-- Program to demonstrate use of parseInt(), parseFloat() and Number() --> <html> <head> <title>Use of parseInt(), parseFloat() and Number()</title> </head> <body> <script> // parseInt(string, radix) document.write("<br>parseInt("10"): " + parseInt("10")); document.write("<br>parseInt("10.33"):" + parseInt("10.33")); document.write("<br>parseInt("34 45 66"):" + parseInt("34 45 66")); document.write("<br>parseInt("40 years"):" + parseInt("40 years")); document.write("<br>parseInt("He was 40"):" + parseInt("He was 40")); document.write("<br>parseInt("10", 10):" + parseInt("10", 10)); document.write("<br>parseInt("10", 8):" + parseInt("10", 8) + "<br>"); // parseFloat(string) document.write("<br>parseFloat("10"):" + parseFloat("10")); document.write("<br>parseFloat("10.00"):" + parseFloat("10.00")); document.write("<br>parseFloat("10.33"):" + parseFloat("10.33") + "<br>"); // Number(object) var x1 = true; var x2 = false; var x3 = new Date(); var x4 = "999"; var x5 = "999 888"; document.write("<br>Number(x1):" + Number(x1)); document.write("<br>Number(x2):" + Number(x2)); document.write("<br>Number(x3):" + Number(x3)); document.write("<br>Number(x4):" + Number(x4)); document.write("<br>Number(x5):" + Number(x5)); </script> </body> </body> </html>
  86. 86. Compiled By - Prof. Rahul S. Tamkhane 2.4 String – Converting number to string (Contd.) ■ In JavaScript, there are three main ways in which any value can be converted to a string. ■ The three approaches for converting to string are: 1) value.toString() 2) "" + value 3) String(value) Unit II - Array, Function and String (14 Marks) 86
  87. 87. Compiled By - Prof. Rahul S. Tamkhane 2.4 String – Converting number to string (Contd.) ■ In JavaScript, there are three main ways in which any value can be converted to a string. ■ The three approaches for converting to string are: 1) value.toString() 2) "" + value 3) String(value) Unit II - Array, Function and String (14 Marks) 87 The toString() method converts a number to a string. Value of radix must be an integer between 2 and 36 Syntax: number.toString([radix]) Example: var num = 15; var a = num.toString(); var b = num.toString(2); var c = num.toString(8); var d = num.toString(16);
  88. 88. Compiled By - Prof. Rahul S. Tamkhane 2.4 String – Converting number to string (Contd.) ■ In JavaScript, there are three main ways in which any value can be converted to a string. ■ The three approaches for converting to string are: 1) value.toString() 2) "" + value 3) String(value) Unit II - Array, Function and String (14 Marks) 88 The plus operator is fine for converting a value when it is surrounded by non-empty strings.
  89. 89. Compiled By - Prof. Rahul S. Tamkhane 2.4 String – Converting number to string (Contd.) ■ In JavaScript, there are three main ways in which any value can be converted to a string. ■ The three approaches for converting to string are: 1) value.toString() 2) "" + value 3) String(value) Unit II - Array, Function and String (14 Marks) 89 The String() function converts the value of an object to a string. The String() function returns the same value as toString() of the individual objects. Syntax: String(object) Example: var x = 15; var res = String(x);
  90. 90. Compiled By - Prof. Rahul S. Tamkhane Unit II - Array, Function and String (14 Marks) 90 <!-- Program to convert number into String --> <html> <head> <title>Convert number into String</title> </head> <body> <script> // Using --- number.toString(radix) var num = 15; document.write("<br>num.toString(): " + num.toString()); document.write("<br>num.toString(2): " + num.toString(2)); document.write("<br>num.toString(8): " + num.toString(8)); document.write("<br>num.toString(16): " + num.toString(16) + "<br><br>"); // Using --- String(object) var x1 = Boolean(0); var x2 = Boolean(1); var x3 = new Date(); var x4 = "12345"; var x5 = 12345; document.write(String(x1) + "<br>"); document.write(String(x2) + "<br>"); document.write(String(x3) + "<br>"); document.write(String(x4) + "<br>"); document.write(String(x5) + "<br>"); </script> </body> </body> </html>
  91. 91. Compiled By - Prof. Rahul S. Tamkhane 2.4 String – Changing the case of string (Contd.) ■ JavaScript provides two methods for changing the case of given string. 1) toLowerCase() – This method converts a string to lowercase. 2) toUpperCase() - This method converts a string to upeercase. Unit II - Array, Function and String (14 Marks) 91 Syntax - string.toLowerCase() Example - var str = "Hello World!"; var res = str.toLowerCase(); Syntax - string.toUpperCase() Example - var str = "Hello World!"; var res = str.toUpperCase();
  92. 92. Compiled By - Prof. Rahul S. Tamkhane Unit II - Array, Function and String (14 Marks) 92 <!-- Program to demonstrate string case change --> <html> <head> <title>String case change</title> <script> function lower() { var str = document.getElementById("input").value; document.getElementById("msg").innerText = str.toLowerCase(); } function upper() { var str = document.getElementById("input").value; document.getElementById("msg").innerText = str.toUpperCase(); } </script> </head> <body> Enter the string <input type="text" id="input" ><br><br> <input type="button" value="UPPERCASE" onclick="upper()"/> <input type="button" value="lowercase" onclick="lower()"/> <p id="msg"></p> </body> </html>
  93. 93. Compiled By - Prof. Rahul S. Tamkhane 2.4 String – Finding Unicode of a character (Contd.) ■ Computer understand the language of numbers. ■ When we enter a character it is automatically converted into a number called as Unicode number ■ The Unicode Standard provides a unique number for every character, no matter what platform, device, application or language. ■ JavaScript has two methods for finding Unicode of character and to convert the number into unicode 1) charCodeAt() 2) fromCharCode() Unit II - Array, Function and String (14 Marks) 93
  94. 94. Compiled By - Prof. Rahul S. Tamkhane 2.4 String – Finding Unicode of a character (Contd.) charCodeAt() – The charCodeAt() method returns the Unicode of the character at the specified index in a string. – We can use the charCodeAt() method together with the length property to return the Unicode of the last character in a string. – The index of the last character is -1, the second last character is -2, and so on (See Example below). Unit II - Array, Function and String (14 Marks) 94 Syntax - string.charCodeAt(index) Example - var str = "HELLO WORLD"; var n = str.charCodeAt(0); // returns 72
  95. 95. Compiled By - Prof. Rahul S. Tamkhane Unit II - Array, Function and String (14 Marks) 95 <!-- Program to display unicode of characters in a string --> <html> <head> <title>Display unicode of characters in a string</title> <script> function myFunction() { var str = "JAVASCRIPT"; var txt = ""; for(i=0; i<str.length; i++) { txt += str.charCodeAt(i) + " "; } document.getElementById("info").innerHTML = txt; } </script> </head> <body> <p>Click the button to display the unicode of characters in the string "JAVASCRIPT".</p> <button onclick="myFunction()">Try it</button> <p id="info"></p> </body> </html>
  96. 96. Compiled By - Prof. Rahul S. Tamkhane 2.4 String – Finding Unicode of a character (Contd.) fromCharCode () – The fromCharCode() method converts Unicode values into characters. – This is a static method of the String object, and the syntax is always String.fromCharCode(). Unit II - Array, Function and String (14 Marks) 96 Syntax - String.fromCharCode(n1, n2, ..., nX) Example - var n = String.fromCharCode (62);
  97. 97. Compiled By - Prof. Rahul S. Tamkhane Unit II - Array, Function and String (14 Marks) 97 <!-- Program to convert unicode number into characters --> <html> <head> <title>Display unicode of characters in a string</title> <script> function myFunction() { var res = "Charcter having Unicode number 65 is: " + String.fromCharCode(65) + "<br>"; var txt = String.fromCharCode(72, 69, 76, 76, 79); document.getElementById("info").innerHTML = res + txt; } </script> </head> <body> <p>Click the button to display the unicode of characters in the string "JAVASCRIPT".</p> <button onclick="myFunction()">Try it</button> <p id="info"></p> </body> </html>
  98. 98. Compiled By - Prof. Rahul S. Tamkhane Unit II - Array, Function and String (14 Marks) 98

×