This document discusses string handling in Java. It explains that strings are immutable objects of type String. It describes the four main string classes in Java - String, StringBuffer, StringBuilder, and StringTokenizer. The document outlines various string methods like length(), charAt(), compareTo(), indexOf(), and replace() among others. It also discusses how to create, modify, search and compare strings in Java.
The document discusses various built-in functions in MySQL for manipulating date, time, string, and numeric data. It describes functions for formatting dates, extracting date elements, adding or subtracting times, concatenating and modifying strings. Common functions covered include DATE_FORMAT(), NOW(), CURDATE(), CONCAT(), REPLACE(), LEFT(), RIGHT(), and MID().
This document defines polymorphism and describes its two types - compile-time and run-time polymorphism. Compile-time polymorphism is demonstrated through method overloading examples, while run-time polymorphism is demonstrated through method overriding examples. The key advantages of polymorphism are listed as code cleanliness, ease of implementation, alignment with real world scenarios, overloaded constructors, and reusability/extensibility.
The document discusses data structures and lists in Python. It begins by defining data structures as a way to organize and store data for efficient access and modification. It then covers the different types of data structures, including primitive structures like integers and strings, and non-primitive structures like lists, tuples, and dictionaries. A large portion of the document focuses on lists in Python, describing how to perform common list manipulations like adding and removing elements using various methods. These methods include append(), insert(), remove(), pop(), and clear(). The document also discusses accessing list elements and other list operations such as sorting, counting, and reversing.
This document discusses object-oriented programming (OOP) concepts like classes, objects, encapsulation, inheritance, and polymorphism. It explains that OOP improves code reusability, modularity, and maintenance by encapsulating data and methods together as objects. Some benefits of OOP include improved communication, seamless design to implementation, and code reuse through inheritance. Potential drawbacks include increased complexity, overhead from derived classes implementing base class functionality, and a high learning curve.
Streams are used to transfer data between a program and source/destination. They transfer data independently of the source/destination. Streams are classified as input or output streams depending on the direction of data transfer, and as byte or character streams depending on how the data is carried. Common stream classes in Java include FileInputStream, FileOutputStream, FileReader, and FileWriter for reading from and writing to files. Exceptions like FileNotFoundException may occur if a file cannot be opened.
Objects in JavaScript can be created using object literals, the new keyword, or Object.create(). Objects are collections of properties and methods that are mutable and manipulated by reference. Arrays are objects that represent ordered collections of values of any type and are created using array literals or the Array constructor. Common array methods include concat, join, pop, push, reverse, and sort. The Math object provides common mathematical functions like pow, round, ceil, floor, random, and trigonometric functions.
Queue is a first-in first-out (FIFO) data structure where elements can only be added to the rear of the queue and removed from the front of the queue. It has two pointers - a front pointer pointing to the front element and a rear pointer pointing to the rear element. Queues can be implemented using arrays or linked lists. Common queue operations include initialization, checking if empty/full, enqueue to add an element, and dequeue to remove an element. The document then describes how these operations work for queues implemented using arrays, linked lists, and circular arrays. It concludes by providing exercises to implement specific queue tasks.
There are 6 types of CSS selectors: simple, class, generic, ID, universal, and pseudo-class selectors. Simple selectors apply styles to single elements. Class selectors allow assigning different styles to the same element on different occurrences. ID selectors define special styles for specific elements. Generic selectors define styles that can be applied to any tag. Universal selectors apply styles to all elements on a page. Pseudo-class selectors give special effects like focus and hover.
Python modules allow for code reusability and organization. There are three main components of a Python program: libraries/packages, modules, and functions/sub-modules. Modules can be imported using import, from, or from * statements. Namespaces and name resolution determine how names are looked up and associated with objects. Packages are collections of related modules and use an __init__.py file to be recognized as packages by Python.
JavaScript is a client-side scripting language that can be inserted into HTML pages to make them interactive. It allows dynamic validation of forms, changing HTML element properties like visibility, and reacting to user events like clicks or form submissions. The Document Object Model (DOM) represents an HTML or XML document as a tree structure, allowing JavaScript to programmatically access and modify the content, structure, and styling of the document. Common built-in JavaScript objects include String, Date, Array, Math, and Boolean, which provide properties and methods for manipulating text, dates, lists of values, numbers, and true/false values.
The Java Stack class implements a last-in, first-out (LIFO) data structure called a stack. It extends the Vector class and inherits its methods. Elements are added to the top of the stack using push() and removed from the top with pop(). The search() method returns the position of an element from the top, and empty() checks if the stack is empty. Common uses of stacks in Java include implementing undo/redo features and evaluating mathematical expressions.
INTRODUCTION
COMPARISON BETWEEN NORMAL FUNCTION AND INLINE FUNCTION
PROS AND CONS
WHY WHEN AND HOW TO USED?
GENERAL STRUCTURE OF INLINE FUNCTION
EXAMPLE WITH PROGRAM CODE
JavaScript is a scripting language that allows adding interactivity to HTML pages. It can be used for client-side form validation and integration with user plugins. JavaScript is case-sensitive and allows variables, functions, conditional statements, and objects. Common uses include pop-up boxes, event handling, and cookies.
Hibernate is an object-relational mapping tool that allows developers to more easily write applications that interact with relational databases. It does this by allowing developers to map Java classes to database tables and columns, so that developers can interact with data through Java objects rather than directly with SQL statements. Hibernate handles the conversion between Java objects and database rows behind the scenes. Some key benefits of using Hibernate include faster data retrieval, avoiding manual database connection management, and easier handling of database schema changes.
The document discusses JavaScript error and exception handling using try, catch, and finally blocks. It provides examples of using try and catch to handle exceptions, catch to retrieve error details, and finally to execute code regardless of exceptions. It also shows how to use window.onerror to handle uncaught exceptions and access error details.
The document provides information about strings in Java including:
1) Strings are objects in Java that are used to hold text data. The String class represents strings and provides various methods to work with strings.
2) There are two ways to create String objects: using string literals or the new keyword. String literals reuse existing objects in the string constant pool.
3) Important String class methods include charAt(), concat(), equalsIgnoreCase(), length(), replace(), substring(), toLowerCase(), toUpperCase(), and trim(). These methods allow manipulating and accessing string values.
The document discusses reading and writing files in Python. It explains that files allow data to be persisted beyond a program's execution and are used to store data on storage devices like hard disks. The main steps for reading and writing files are to open the file, use it (read from or write to it), and close the file. It also provides examples of opening file streams in read and write modes, and using methods like read(), readline(), and write() to interact with files.
HTML is a markup language that is used to define the structure and layout of web pages. HTML uses tags to describe paragraphs, headings, lists, links, and other items that make up a web page. Some key HTML tags include <html> to define an HTML document, <head> for metadata, <title> for the page title, <body> for the visible page content, headings <h1> to <h6>, paragraphs <p>, and lists <ul>, <ol>, and <dl>. HTML also supports images <img>, forms <form> with input elements like text fields <input>, textareas <textarea>, buttons <button>, and select lists <select>. Styles can be added to HTML
The document discusses various concepts related to arrays in C/C++ including:
- What an array is and its key properties like contiguous memory locations and common data type
- Different types of arrays like single dimensional and multi dimensional
- How to declare, initialize and access array elements
- Passing arrays to functions
- Searching and sorting arrays
- Common array operations like insertion and deletion
The document discusses JavaScript, including its history and differences from Java. It describes JavaScript's uses in modifying HTML documents dynamically and embedding it in HTML. The document outlines JavaScript's object-based nature, primitive data types, variables, operators, and functions. It provides examples of numeric, string, and boolean literals as well as type conversions.
- Java threads allow for multithreaded and parallel execution where different parts of a program can run simultaneously.
- There are two main ways to create a Java thread: extending the Thread class or implementing the Runnable interface.
- To start a thread, its start() method must be called rather than run(). Calling run() results in serial execution rather than parallel execution of threads.
- Synchronized methods use intrinsic locks on objects to allow only one thread to execute synchronized code at a time, preventing race conditions when accessing shared resources.
This document discusses different types of SQL functions including string, numeric, conversion, group, date/time, and user-defined functions. It provides examples of common string functions like UPPER, LENGTH, SUBSTR. Numeric functions covered include ABS, ROUND, POWER. Group functions include AVG, COUNT, MAX, MIN, SUM. Date functions allow conversion and calculation involving dates. The document demonstrates how to create scalar and table-valued user-defined functions in SQL.
This document discusses Java strings and provides information about:
1. What strings are in Java and how they are treated as objects of the String class. Strings are immutable.
2. Two ways to create String objects: using string literals or the new keyword.
3. Important string methods like concatenation, comparison, substring, and length; and string classes like StringBuffer and StringBuilder that allow mutability.
Stored procedures and functions are named PL/SQL blocks that are stored in a database. They improve performance by reducing network traffic and allowing shared memory usage. Stored procedures are created using the CREATE PROCEDURE statement and can accept parameters using modes like IN, OUT, and IN OUT. Stored functions are similar but return a value. Packages group related database objects like procedures, functions, types and provide modularity and information hiding.
This document provides information on Java servlets including: what servlets are and their advantages; the servlet architecture and lifecycle including initialization, processing requests via doGet and doPost methods, and destruction; how to deploy servlets in an application server; and how servlets handle form data submission. Servlets act as a middle layer between web requests and applications/databases, and allow dynamically generating web pages.
This document discusses advance object-oriented programming concepts. It covers procedural programming vs object-oriented programming, features of OOP like classes, objects, inheritance and polymorphism. It also discusses OOP design principles like single responsibility, open-closed, Liskov substitution, dependency inversion and interface segregation principles. Examples are provided to explain concepts like inheritance, polymorphism, abstraction and interfaces. The document provides a comprehensive overview of key OOP concepts and design principles.
Queue is a first-in first-out (FIFO) data structure where elements can only be added to the rear of the queue and removed from the front of the queue. It has two pointers - a front pointer pointing to the front element and a rear pointer pointing to the rear element. Queues can be implemented using arrays or linked lists. Common queue operations include initialization, checking if empty/full, enqueue to add an element, and dequeue to remove an element. The document then describes how these operations work for queues implemented using arrays, linked lists, and circular arrays. It concludes by providing exercises to implement specific queue tasks.
There are 6 types of CSS selectors: simple, class, generic, ID, universal, and pseudo-class selectors. Simple selectors apply styles to single elements. Class selectors allow assigning different styles to the same element on different occurrences. ID selectors define special styles for specific elements. Generic selectors define styles that can be applied to any tag. Universal selectors apply styles to all elements on a page. Pseudo-class selectors give special effects like focus and hover.
Python modules allow for code reusability and organization. There are three main components of a Python program: libraries/packages, modules, and functions/sub-modules. Modules can be imported using import, from, or from * statements. Namespaces and name resolution determine how names are looked up and associated with objects. Packages are collections of related modules and use an __init__.py file to be recognized as packages by Python.
JavaScript is a client-side scripting language that can be inserted into HTML pages to make them interactive. It allows dynamic validation of forms, changing HTML element properties like visibility, and reacting to user events like clicks or form submissions. The Document Object Model (DOM) represents an HTML or XML document as a tree structure, allowing JavaScript to programmatically access and modify the content, structure, and styling of the document. Common built-in JavaScript objects include String, Date, Array, Math, and Boolean, which provide properties and methods for manipulating text, dates, lists of values, numbers, and true/false values.
The Java Stack class implements a last-in, first-out (LIFO) data structure called a stack. It extends the Vector class and inherits its methods. Elements are added to the top of the stack using push() and removed from the top with pop(). The search() method returns the position of an element from the top, and empty() checks if the stack is empty. Common uses of stacks in Java include implementing undo/redo features and evaluating mathematical expressions.
INTRODUCTION
COMPARISON BETWEEN NORMAL FUNCTION AND INLINE FUNCTION
PROS AND CONS
WHY WHEN AND HOW TO USED?
GENERAL STRUCTURE OF INLINE FUNCTION
EXAMPLE WITH PROGRAM CODE
JavaScript is a scripting language that allows adding interactivity to HTML pages. It can be used for client-side form validation and integration with user plugins. JavaScript is case-sensitive and allows variables, functions, conditional statements, and objects. Common uses include pop-up boxes, event handling, and cookies.
Hibernate is an object-relational mapping tool that allows developers to more easily write applications that interact with relational databases. It does this by allowing developers to map Java classes to database tables and columns, so that developers can interact with data through Java objects rather than directly with SQL statements. Hibernate handles the conversion between Java objects and database rows behind the scenes. Some key benefits of using Hibernate include faster data retrieval, avoiding manual database connection management, and easier handling of database schema changes.
The document discusses JavaScript error and exception handling using try, catch, and finally blocks. It provides examples of using try and catch to handle exceptions, catch to retrieve error details, and finally to execute code regardless of exceptions. It also shows how to use window.onerror to handle uncaught exceptions and access error details.
The document provides information about strings in Java including:
1) Strings are objects in Java that are used to hold text data. The String class represents strings and provides various methods to work with strings.
2) There are two ways to create String objects: using string literals or the new keyword. String literals reuse existing objects in the string constant pool.
3) Important String class methods include charAt(), concat(), equalsIgnoreCase(), length(), replace(), substring(), toLowerCase(), toUpperCase(), and trim(). These methods allow manipulating and accessing string values.
The document discusses reading and writing files in Python. It explains that files allow data to be persisted beyond a program's execution and are used to store data on storage devices like hard disks. The main steps for reading and writing files are to open the file, use it (read from or write to it), and close the file. It also provides examples of opening file streams in read and write modes, and using methods like read(), readline(), and write() to interact with files.
HTML is a markup language that is used to define the structure and layout of web pages. HTML uses tags to describe paragraphs, headings, lists, links, and other items that make up a web page. Some key HTML tags include <html> to define an HTML document, <head> for metadata, <title> for the page title, <body> for the visible page content, headings <h1> to <h6>, paragraphs <p>, and lists <ul>, <ol>, and <dl>. HTML also supports images <img>, forms <form> with input elements like text fields <input>, textareas <textarea>, buttons <button>, and select lists <select>. Styles can be added to HTML
The document discusses various concepts related to arrays in C/C++ including:
- What an array is and its key properties like contiguous memory locations and common data type
- Different types of arrays like single dimensional and multi dimensional
- How to declare, initialize and access array elements
- Passing arrays to functions
- Searching and sorting arrays
- Common array operations like insertion and deletion
The document discusses JavaScript, including its history and differences from Java. It describes JavaScript's uses in modifying HTML documents dynamically and embedding it in HTML. The document outlines JavaScript's object-based nature, primitive data types, variables, operators, and functions. It provides examples of numeric, string, and boolean literals as well as type conversions.
- Java threads allow for multithreaded and parallel execution where different parts of a program can run simultaneously.
- There are two main ways to create a Java thread: extending the Thread class or implementing the Runnable interface.
- To start a thread, its start() method must be called rather than run(). Calling run() results in serial execution rather than parallel execution of threads.
- Synchronized methods use intrinsic locks on objects to allow only one thread to execute synchronized code at a time, preventing race conditions when accessing shared resources.
This document discusses different types of SQL functions including string, numeric, conversion, group, date/time, and user-defined functions. It provides examples of common string functions like UPPER, LENGTH, SUBSTR. Numeric functions covered include ABS, ROUND, POWER. Group functions include AVG, COUNT, MAX, MIN, SUM. Date functions allow conversion and calculation involving dates. The document demonstrates how to create scalar and table-valued user-defined functions in SQL.
This document discusses Java strings and provides information about:
1. What strings are in Java and how they are treated as objects of the String class. Strings are immutable.
2. Two ways to create String objects: using string literals or the new keyword.
3. Important string methods like concatenation, comparison, substring, and length; and string classes like StringBuffer and StringBuilder that allow mutability.
Stored procedures and functions are named PL/SQL blocks that are stored in a database. They improve performance by reducing network traffic and allowing shared memory usage. Stored procedures are created using the CREATE PROCEDURE statement and can accept parameters using modes like IN, OUT, and IN OUT. Stored functions are similar but return a value. Packages group related database objects like procedures, functions, types and provide modularity and information hiding.
This document provides information on Java servlets including: what servlets are and their advantages; the servlet architecture and lifecycle including initialization, processing requests via doGet and doPost methods, and destruction; how to deploy servlets in an application server; and how servlets handle form data submission. Servlets act as a middle layer between web requests and applications/databases, and allow dynamically generating web pages.
This document discusses advance object-oriented programming concepts. It covers procedural programming vs object-oriented programming, features of OOP like classes, objects, inheritance and polymorphism. It also discusses OOP design principles like single responsibility, open-closed, Liskov substitution, dependency inversion and interface segregation principles. Examples are provided to explain concepts like inheritance, polymorphism, abstraction and interfaces. The document provides a comprehensive overview of key OOP concepts and design principles.
The document discusses arrays in JavaScript. It defines an array as an indexed list of elements. It provides examples of declaring and initializing arrays. It also discusses advantages of using arrays, such as being able to iterate over elements using a for loop. The document covers various array methods like sort() and reverse() and provides an example program that prompts the user for words, stores them in an array, and displays them sorted and unsorted. It concludes by mentioning the topic of the next lecture will be functions and variable scope.
This document contains summaries of JavaScript concepts including arrays, strings, setInterval and clearInterval functions. It defines arrays as ordered collections of values that can be one or multi-dimensional. It also describes common string methods like charAt(), charCodeAt(), and slice(). Finally, it explains that setInterval calls a function repeatedly at specified intervals until clearInterval is called to stop it.
This document discusses control structures and break and continue statements in JavaScript. It begins by providing an example of a for loop that counts from 1 to 6000. It then discusses arrays in JavaScript, including how to declare and access single and multi-dimensional arrays. Some key array methods like reverse() and sort() are also mentioned. The document concludes by explaining how to write a web page that prompts the user for 10 words and displays them in sorted order.
Arrays in JavaScript can store multiple data types. Common array methods allow users to manipulate array elements by adding, removing, and modifying items. Key methods include toString() and join() to convert arrays to strings, concat and push/pop to modify arrays, and filter(), map(), and reduce() to transform array elements.
Arrays in JavaScript can be used to store multiple values in a single variable. Arrays are objects with numeric indexes and various methods that can be used to modify arrays. Some key array methods include concat(), join(), push(), pop(), unshift(), shift(), sort(), reverse(), slice(), splice(), indexOf(), lastIndexOf(), and length. Arrays are dynamically typed and sparse, allowing elements to contain values of any type.
Arrays in JavaScript can be used to store multiple values in a single variable. Arrays are objects with numeric indexes and various methods that can be used to modify arrays. Some key array methods include concat(), join(), push(), pop(), unshift(), shift(), sort(), reverse(), slice(), splice(), indexOf(), lastIndexOf(), and length. Arrays are dynamically typed and sparse, allowing elements to contain values of any type.
This document provides information on JavaScript arrays. It discusses how arrays allow storing multiple values in a variable, unlike variables declared with var or let which can only store one value. The document covers traversing arrays, and performing CRUD (create, read, update, delete) operations on arrays using methods like push(), pop(), splice(), etc. It also explains how to use array methods like map(), filter() and reduce() to transform or filter array elements. Finally, it provides examples of using these methods to process product data from an array of objects.
An array is collection of similar kind of data elements which can store same data types and we can not store some of int and some of float data types in Array.
This document provides an overview of key JavaScript concepts including variables, data types, operators, functions, objects, arrays, and booleans. It explains how to declare and assign variables, define functions, create and manipulate objects and arrays, and use comparison operators to evaluate conditions. The document also describes common JavaScript math, string, and array methods for performing operations on variables and values.
Covers Arrays in JavaScript,
Various types of declaration and initializations,
Associative Arrays,
Nesting Arrays,
Array Functions etc.
Video tutorials available at http://youtube.com/techcbt-online
The document discusses arrays in JavaScript. It defines arrays as data structures that can hold related items and notes they are dynamic. Arrays in JavaScript allow each element to be referenced by its index number starting from zero. Individual elements can be accessed using the name of the array, brackets, and the element index number. The length property allows arrays to know their size. Examples are provided for declaring, initializing, and manipulating arrays including using for loops and passing arrays to functions.
This presentation highlights project development using software development life cycle (SDLC) with a major focus on incorporating research in the design phase to develop innovative solution. Some case-studies are also highlighted which makes the reader to understand the different phases with practical examples.
11th International Conference on Data Mining (DaMi 2025)kjim477n
Welcome To DAMI 2025
Submit Your Research Articles...!!!
11th International Conference on Data Mining (DaMi 2025)
July 26 ~ 27, 2025, London, United Kingdom
Submission Deadline : June 07, 2025
Paper Submission : https://csit2025.org/submission/index.php
Contact Us : Here's where you can reach us : [email protected] or [email protected]
For more details visit : Webpage : https://csit2025.org/dami/index
Impurities of Water and their Significance.pptxdhanashree78
Impart Taste, Odour, Colour, and Turbidity to water.
Presence of organic matter or industrial wastes or microorganisms (algae) imparts taste and odour to water.
Presence of suspended and colloidal matter imparts turbidity to water.
May 2025: Top 10 Read Articles Advanced Information Technologyijait
International journal of advanced Information technology (IJAIT) is a bi monthly open access peer-reviewed journal, will act as a major forum for the presentation of innovative ideas, approaches, developments, and research projects in the area advanced information technology applications and services. It will also serve to facilitate the exchange of information between researchers and industry professionals to discuss the latest issues and advancement in the area of advanced IT. Core areas of advanced IT and multi-disciplinary and its applications will be covered during the conferences.
A SEW-EURODRIVE brake repair kit is needed for maintenance and repair of specific SEW-EURODRIVE brake models, like the BE series. It includes all necessary parts for preventative maintenance and repairs. This ensures proper brake functionality and extends the lifespan of the brake system
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSsamueljackson3773
In this paper, the author discusses the concerns of using various wireless communications and how to use
them safely. The author also discusses the future of the wireless industry, wireless communication
security, protection methods, and techniques that could help organizations establish a secure wireless
connection with their employees. The author also discusses other essential factors to learn and note when
manufacturing, selling, or using wireless networks and wireless communication systems.
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyYannis
The doctoral thesis trajectory has been often characterized as a “long and windy road” or a journey to “Ithaka”, suggesting the promises and challenges of this journey of initiation to research. The doctoral candidates need to complete such journey (i) preserving and even enhancing their wellbeing, (ii) overcoming the many challenges through resilience, while keeping (iii) high standards of ethics and (iv) scientific rigor. This talk will provide a personal account of lessons learnt and recommendations from a senior researcher over his 30+ years of doctoral supervision and care for doctoral students. Specific attention will be paid on the special features of the (i) interdisciplinary doctoral research that involves Information and Communications Technologies (ICT) and other scientific traditions, and (ii) the challenges faced in the complex technological and research landscape dominated by Artificial Intelligence.
David Boutry - Mentors Junior DevelopersDavid Boutry
David Boutry is a Senior Software Engineer in New York with expertise in high-performance data processing and cloud technologies like AWS and Kubernetes. With over eight years in the field, he has led projects that improved system scalability and reduced processing times by 40%. He actively mentors aspiring developers and holds certifications in AWS, Scrum, and Azure.
First Review PPT gfinal gyft ftu liu yrfut goSowndarya6
CyberShieldX provides end-to-end security solutions, including vulnerability assessment, penetration testing, and real-time threat detection for business websites. It ensures that organizations can identify and mitigate security risks before exploitation.
Unlike traditional security tools, CyberShieldX integrates AI models to automate vulnerability detection, minimize false positives, and enhance threat intelligence. This reduces manual effort and improves security accuracy.
Many small and medium businesses lack dedicated cybersecurity teams. CyberShieldX provides an easy-to-use platform with AI-powered insights to assist non-experts in securing their websites.
Traditional enterprise security solutions are often expensive. CyberShieldX, as a SaaS platform, offers cost-effective security solutions with flexible pricing for businesses of all sizes.
Businesses must comply with security regulations, and failure to do so can result in fines or data breaches. CyberShieldX helps organizations meet compliance requirements efficiently.
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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. Compiled By - Prof. Rahul S. Tamkhane
2.1 Array – Sorting an Array element
Unit II - Array, Function and String (14 Marks) 20
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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. Compiled By - Prof. Rahul S. Tamkhane
2.1 Array – Objects as an Associative Array
Unit II - Array, Function and String (14 Marks) 32
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. 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. 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. 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. Compiled By - Prof. Rahul S. Tamkhane
2.2 Functions – Writing a function (Contd.)
Unit II - Array, Function and String (14 Marks) 37
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. 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. Compiled By - Prof. Rahul S. Tamkhane
2.2 Functions – Adding an arguments
(Contd.)
Unit II - Array, Function and String (14 Marks) 40
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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. Compiled By - Prof. Rahul S. Tamkhane Unit II - Array, Function and String (14 Marks) 98