Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Course: Client Side Scripting, Prepared By: Atul Kabra, 9422279260

Java Script Lecture-14


Topic: Methods of String

String length:
The length property has the string length.
Please note that str.length is a numeric property, not a function. There is no
need to add parenthesis after it.

Accessing Character:
To get a character at position pos, use square brackets [pos] or call the
method str.charAt(pos). The first character starts from the zero position:
var str = `Hello`; // the first character
alert( str[0] ); // H
alert( str.charAt(0) ); // H

Iterating String :
We can also iterate over characters using for..of:
for (var char of "Hello") {
alert(char); // H,e,l,l,o (char becomes "H", then "e", then "l" etc)
}

Strings are immutable :


Strings can’t be changed in JavaScript. It is impossible to change a
character.
Let’s try it to show that it doesn’t work:
var str = 'Hi';
str[0] = 'h'; // no effect
alert( str ); // Hi

Course: Java Script, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Client Side Scripting, Prepared By: Atul Kabra, 9422279260

Changing the case :


Methods toLowerCase() and toUpperCase() change the case:
alert( 'Interface'.toUpperCase() ); // INTERFACE
alert( 'Interface'.toLowerCase() ); // interface

Searching for substring :


1) indexOf() method
Syntax: str.indexOf(substr, pos)

It looks for the substr in str, starting from the given position pos, and
returns the position where the match was found or -1 if nothing can be
found.
If we’re interested in all occurrences, we can run indexOf in a loop. Every
new call is made with the position after the previous match:

var s = 'I felt happy because I saw the others were happy and because I knew I
should feel happy, but I wasn’t really happy.';
var pos=0;
while(true){
pos=s.indexOf("happy",pos);
if(pos==-1) break;

alert(`found at ${pos}`);
pos++; // continue the search from the next position
}
Output: found at 7
found at 43
found at 82
found at 109

2) search() method
Syntax: str.search(searchvalue);

Course: Java Script, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Client Side Scripting, Prepared By: Atul Kabra, 9422279260

This method is just same as indexOf(), only difference is here search value
can be string or regular expression.

3) includes() method
The more modern method
str.includes(substr, pos)
returns true/false depending on whether str contains substr within.

It’s the right choice if we need to test for the match, but don’t need its
position:

4) The methods str.startsWith() and str.endsWith() do exactly what they


say:

Getting substring
There are 3 methods in JavaScript to get a substring:
substring(), substr() and slice().
1) slice( )
Syntax: str.slice(start [, end])

Returns the part of the string from start to (but not including) end.
Example:
var str = "Info Planet”;
alert( str.slice(0, 3) ); // 'Inf', the substring from 0 to 3 (not including 3)
alert( str.slice(0, 1) ); // 'I', from 0 to 1, but not including 1, so only character at 0

Negative values for start/end are also possible. They mean the position is
counted from the string end:
var str = "stringify";

Course: Java Script, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Client Side Scripting, Prepared By: Atul Kabra, 9422279260

// start at the 4th position from the right, end at the 1st from the
right
alert( str.slice(-4, -1) ); // gif

2) substring( )
Syntax: str.substring(start [, end])

Returns the part of the string between start and end.


This is almost the same as slice, but it allows start to be greater
than end.
Example:
var str = "stringify";

// these are same for substring


alert( str.substring(2, 6) ); // "ring"
alert( str.substring(6, 2) ); // "ring"

// ...but not for slice:


alert( str.slice(2, 6) ); // "ring" (the same)
alert( str.slice(6, 2) ); // "" (an empty string)

3) substr ( )
Syntax: str.substr(start [, length])
Returns the part of the string from start, with the given length. (Allows
negative start also)
In contrast with the previous methods, this one allows us to specify
the length instead of the ending position:
var str = "stringify";
alert( str.substr(2, 4) ); // ring, from the 2nd position get 4 characters

Course: Java Script, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Client Side Scripting, Prepared By: Atul Kabra, 9422279260

Joining a String:
In JavaScript we have two ways to concatenate (join) strings
1. Using + operator
2. Using concat() function of String object.
Syntax : string.concat(string1, string2,….,stringN);

Dividing String using split() method:


The split() method creates a new array and then copies portions of the
strings into its array elements.
You must tell the split() method what string (separator/delimiter) is used to
separate substrings in the string.

Syntax: string.split(separator,[limit]);

For example,
var s = "Info Planet, Opp. M. J. College, Below Axis ATM, Jalgaon";
var a = s.split(',');
console.log(a);
limit (optional) parameter limits the number of elements returned in the
array.

Converting String to Number:


1) parseInt()
It converts a string into an integer.

var size=’56inch’;
var integer =parseInt(size,10); // 56

Simillary parseFloat()

2) Number()
The Number() method converts a string to a number. If string consist of
only number then you will get expected outcome otherwise it will return
NaN.
var size=’56inch’; var size=’56’;
var integer =Number (size); //NaN var integer =Number(size); //56

Course: Java Script, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Client Side Scripting, Prepared By: Atul Kabra, 9422279260

Converting Number to String:


1) toString()
The toString() method can be used to convert both integers and floats to
corresponding string.
var num=100;
var str = num.toString(); //”100”
2) concatenation +
var str=””+num; //”100”

Finding a Unicode of a Character:


1) charCodeAt( )
charCodeAt() is a string method that is used to retrieve a Unicode value for
a character at a specific position.

Syntax: string.charCodeAt([position]);
If the position parameter is not provided, then it will use 0 position by
default. Means returns the code of first character of string.

2) fromCharCode( )
It is a String method that is used to create a string from a sequence of
Unicode Values.

Syntax: String.fromCharCode(value1, value2, ……., valueN);


For example:
var str = String.fromCharCode(65,66,67,68); //ABCD

Course: Java Script, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Client Side Scripting, Prepared By: Atul Kabra, 9422279260

Summary of String Methods

Sr. No Method Description


1 charAt() Returns the character at the specified index.
2 charCodeAt() Returns Unicode value of the character specified by an index.
3 concat() Concate strings and returns new String.
4 indexOf() Returns first occurrence of the specified value , or -1 if not found.
5 search() This method search for a match of specified string or regular
expression.
6 slice() Extracts a section of string and returns a new string.
7 split() Splits a string objects into an array of strings.
8 substr() Returns substring beginning at the specified position through the
specified number of charaters.
9 substring() Returns substring in a string between two indexes into the string.
10 toLoserCase() Returns lower case string
11 toUpperCase() Returns upper case string
12 toString() Returns string representation.

Course: Java Script, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260

You might also like