Newby Coder header banner

Javascript Strings


Strings as objects

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


Finding length of a string

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


Retrieving a specific string character

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


Searching fpr substring inside a string

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

Retrieving Substring


Changing to upper or lowercase

Methods toLowerCase() and toUpperCase() convert characters of a string to lower or uppercase

const dudey = 'Who iS a DudE';
dudey.toLowerCase();
dudey.toUpperCase();

Replacing parts of a string

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');