Most things are objects in JavaScript
For example when a string is created by using
let string = 'This is my string';
variable string becomes a string object instance, and as a result has a number of properties and methods available to it
length
property is used to find length of string
var phoneType = 'Redmi 2';
var len = phoneType.length;
Value of variable len is 7, which includes a space character between Redmi and 2
A character inside a string can be returned by using square bracket notation ([]
)
Inside square brackets, index (or position) of the character to be returned is specified
Index is counted from 0, so for example to retrieve first letter :
phoneType[0];
returns R
To retrieve last character of a string:
browserType[browserType.length-1];
Length of "Redmi 2" is 7, but character position is 6 because count starts at 0, and hence length-1
indexOf()
method can be used to check if a substring is present
It accepts a single parameter, i.e. the substring to be searched and returns
phoneType.indexOf('mi');
This returns 2, which is the position of first character of substring
phoneType.indexOf('mid');
returns -1
slice()
can be used to extract a substring from a string :phoneType.slice(0,3);
returns Red
slice()
takes two arguments, of which second one is optional
To extract all remaining characters in a string after a certain character, second parameter is omitted
phoneType.slice(3);
returns mi 2
Methods toLowerCase()
and toUpperCase()
convert characters of a string to lower or uppercase
const dudey = 'Who iS a DudE';
dudey.toLowerCase();
dudey.toUpperCase();
A substring inside a string can be replaced with another substring using replace()
method
It takes two parameters — string that is to be replaced, and string to be replaced with
phoneType.replace('redm','M');
This returns updated value, i.e. Mi 2 but doesn't update value of phoneType
variable
To actually get updated value reflected in phoneType
variable, result of operation has to be set to a variable
phoneType = phoneType.replace('redm', 'M');