Strings in Javascript

Strings in Javascript

In this blog, we will explore the string and its methods & properties in Javascript

Anusha V's photo
Anusha V
·May 22, 2022·

9 min read

Subscribe to our newsletter and never miss any upcoming articles

Play this article

In our Javascript Datatype blog, we have seen about string datatype and now we are going to explore the string concept in depth

What is a string?

A string is a sequence of characters stored in a variable and it is enclosed within a double or single quote.

Example:-

let str1 = “Life is full of mystery”;

We can also specify single quotes within double quotes and vice-versa.

Example:-

let str2= “Life isfullof mystery”;

From the above example is clear that we can’t use same quotes to surround and also inside the string characters. So, if we want to use do it, we can give it using escape characters.

Let us take a scenario,

if we try to give the same quotes to surround and also inside the string characters, let’s see what will be happening

let = "Life is "full" of mystery";//Shows an error

The above example shows an error when we try to use the same quotes to surround and also inside the string characters.

In this case, we can use escape characters to solve this problem.

Let us take an example,

let str2 = “Life is \”Full”\ of mystery”;

In the above example, we are using an escape character \”, \’ and it will insert the respective quotes and it will not show an error.

String Property and Methods:-

  • Strings in Javascript have properties and methods that can be executed to manipulate the string characters.

  • You might think String is not an object, so it doesn't have methods and properties but here in the javascript consider everything as an object (i.e., Javascript treats Primitive values such as string, number, and array as an object). So, strings have methods and properties to apply to manipulate them.

length property:-

The length property is used to return the length of the string.

Let us take an example,

let str = “Life is full of mystery”;
console.log(str.length); //23

In the above example, the length of the entire string is calculated. Empty space is also calculated as a character. So, in the above example totally 23 characters are stored in the str variable. Therefore, the String length is 23.

How to extract a part of a string?

There are three methods to extract a part of the string, are

  • Slice(start,end)
  • Substring(start,end)
  • Substr(start,length)

1. Slice(start,end):-

  • slice() method is used to extract a part of the string.
  • To extract the part of the string, we will use its index value to extract it.
  • The index value starts from zero.
  • It has two parameters start and end value.
  • The start value is included and the end value is excluded.

Let us understand with an example,

let str = “Life is full of mystery”;
let str1 = str.slice(4,9);
console.log(str1);//is f

In the above example, we are extracting the part of a string starting from the index position 4 to 8 because the end value is excluded so it is extracting it till the 8th index position.

Note:- whitespace and commas will also be considered as a character.

We can also specify the negative index values to extract the part of the string.

Let us understand by example,

let str = “Life is full of mystery”;
let str1 = str.slice(-9,-4);
console.log(str1); //f mys

In the above example, it is the same as specifying a positive value only one change is that we are extracting a string from the position at end of the string.

2.Substring(start,end):-

  • Substring() method is same as slice() method.
  • Substring() method can’t extract a part of a string using a negative index value.

Let us understand with an example,

let str = “Life is full of mystery”;
let str1 = str.substring(4,9);
console.log(str1);//is f

3.Substr(start,length):-

Substr() method is similar to before methods we have seen. The only difference is that in other methods, we will give the end value but here we will mention the start index value till which length of the string it should extract.

Let us understand with an example,

let str = “Life is full of mystery”;
let str1 = str.substr(4,4);
console.log(str1);//is

In the above example, we are mentioning the starting index value to till which length of the string(i.e., part of the string) it should extract.

replace() method:-

replace() method is used to replace the specified value with another value in the string.

Let us understand by example,

let str = “Life is full of mystery”;
let str1 = str.replace(m,s);
console.log(str1);// Life is full of systery

In the above example, the “m” character in the string is changed to another value “S” in the string using replace() method.

toUperCase() and toLowerCase() methods:-

To change the string to uppercase or in lowercase, we use the toUpperCase() and toLowerCase() methods.

Let us understand by example,

let str = “Life is full of mystery”;
let str1 = str.toUpperCase();
console.log(str1);// LIFE IS FULL OF MYSTERY

let str = “Life is full of mystery”;
let str1 = str.toLowerCase();
console.log(str1);// life is full of mystery

Concat() Method:-

  • Concat() method is used to concat two or more strings.
  • Before, the concat() method to concatenate the strings we used the “+” operator.

Let us understand by example,

let str = “Life is full”;
let str1 = str.concat(" ", "of mystery");
console.log(str1);//Life is full of mystery

trim() method:-

trim() method is used to remove whitespace on both sides of strings.

Let us understand by example,

let x = ”    Life is full of mystery     “;
let y = x.trim();
console.log(y); //Life is full of mystery

In the above example, the trim() method removes the whitespaces around the string. It is mostly used in form validation.

Extracting a character in the string:-

There are three methods to extract a character in a string are,

  • charAt(position)
  • charCodeAt(position)
  • Property access[]

1.charAt(position):- In this method, we will use the position (i.e., an index value) of that character to extract it.

Let us understand by example,

let x = “Life”;
let y = x.charAt(2);
console.log(y); //f

In the above example, we are extracting the character in the second index position in the string.

2.charCodeAt(position):-

This method will return the Unicode of the character whose index position is specified.

Let us understand by example,

let x = “Life”;
let y = x.charCodeAt(2);
console.log(y); //102

In the above example, we are mentioning the index position of the character whose Unicode needed to be returned. Here in our example Unicode of “f’ is 102.

3.Property Access[]:-

First, let us see an example,

let x = “life”;
console.log(x[0]); //l

The above example may look like an array. but, they are not an array.

  • It returns the character according to the index value mentioned, as same as in the array. But as we do in the array we can’t reassign value to it.

  • If no character is found, it will return as undefined.

    Converting a string into an array:-

  • If we need to convert a string into an array, we will use the split() method.

  • Inside the split() method, we will specify the character at which place it needs to be split into different parts(i.e., array characters).
  • We call it a separator.
  • If we didn’t mention the separator, it will consider the whole string as an array index value 0. Let us understand by example,
let x = “Life is full of mystery”
let y = x.split( ‘  ’ );
console.log(y); //[ 'Life', 'is', 'full', 'of', 'mystery' ]

In the above example, we are converting a string into an array by using white space as a separator(i.e., it is splitting into array elements wherever the white spaces are there).

String Search Methods:-

There are 4 most commonly used search methods in string are,

  • indexOf()
  • startsWith()
  • endsWith()
  • lastindexOf()

1. indexOf():-

  • indexOf() method is used to identify the index position of the character or part of the string that we need to search.
  • It will return the first occurrence of the character or part of the string that we are searching for. We can search for the character or part of the string with the indexOf() method in four ways, are

i) indexOf(ch):-

In a first way, we will mention the character which we need to search in the given string and return its index position.
It will return the index position of the first occurrence of the character or part of the string.

Let us take an example,

let x = “life is full of mystery”;
let y = x.indexOf(“f”); 
console.log(y); //2

In the above example, it will search and returns the index position of the “f” character in that string.

ii).indexOf(ch,index):-

In this method, we will mention the character which we need to search and also an index value from which position(i.e., an index value) we need to start to search that character in that string.

Let us understand by example,

let x = “life is full of mystery”;
let y = x.indexOf(“f”,7); 
console.log(y); //8

In the above example, we are searching for an “f” character after the 7th index position in the string and it returns the index value.

iii)indexOf(str):-

In this method, we are searching for a part of the string and returns the index value of the first character of the specified part of the string.

Let us understand by example,
let x = “life is full of mystery”;
let y = x.indexOf(“of”); 
console.log(y); //13

In the above example, we are searching for a part of the string(i.e., of) and it returns the index position of the first character “o” (i.e., 13).

iv) indexOf(str,index):-

In this method, we are searching for a part of the string and return the index value of the first character of the specified part of the string and we also mention the index value from which index value it should start to search.

Let us understand by example,

let x = “life is full of mystery”;
let y = x.indexOf(“of”,16); 
console.log(y); //error

In the above example, we are searching for a part of the string(i.e., of) and it returns an error because we are mentioning an index position from where it should search. So, here in our example, it can't find “of” the string after the index value 16. Therefore it returns an error.

2. lastindexOf():-

lastindexOf() method is similar to indexOf(), the only change is that it will search for the character specified in the string from the last position of the string and returns its index value.

let us understand by example

let x = “life is full of mystery”;
let y = x.lastindexOf(“f”); 
console.log(y); //13

3. startsWith():-

  • startswith() method returns true or false.
  • It returns true if the character or part of the string begins with the given string or else it returns false.

let us understand by example,

  • let x = “life is full of mystery”;
  • let y = “x.startsWith(“life”);
  • console.log(y); //true

In the above example, we are checking if the x variable begins with the “life” string or not, and then it returns true or false.

We can also mention from which index position we want to check its beginning.

For example,

let x = “life is full of mystery”;
let y = “x.startsWith(“of”, 17);
console.log(y); //false

4.endsWith():-

endsWith() method is similar to the startsWith(), only one change is that it will check that the specified string is at the end of the string or not.

Let us understand by example,

let x = “life is full of mystery”;
let y = x.endsWith(‘mystery’);
console.log(y); //true

In the above example, it returns true because the string ends with the specified string(i.e., mystery).

In the next blog we will explore about number concept in Javascript.

 
Share this