JavaScript Array and string methods

kanon chakma
2 min readNov 2, 2020

Sometimes we need to do different task with string and Array.In this article we will discuss about string and array methods

let string=“welcome”

1.charAt(index)

This method return the specific character that based on index. console.log(string.charAt(1)) //output: “e”;

2.concat()

let string1= “hello”; let string2= “buddy”;

when we need to add two or more string, concat() method are used.There are different methods to add string such as “ console.log(string1+string2)” or “console.log(string1.concat(string2))” both //output :“hello buddy”

3.indexOf()

let string1= “hello buddy how are you?”;

For finding any character or string index, we can use indexof method. When there is no exist searching text it will return -1.

console.log( “ index is ”, string1.indexOf(buddy)) // output: index is 6. console.log ( “ index is ” , string1.indexOf(e)) //output:index is 1.

4.slice()

let string1= “hello buddy how are you?”;

slice method used to cut a part of a string and return those part in a new string. When we pass only one parameter it cut the string from this position.

const string2=string1.slice(5,10)//output:buddy.

5.replace()

let string1= “hello buddy how are you?”;

This method replace a specific value or text with another text in a string. console.log(string1.replace(“how”, “who”))

//output:hello buddy who are you?.

6.lastIndexOf()

let string1= “hello buddy how are you how?”;

This method search specific index from end of the beginning.It return last occurrence searching text.

console.log(“index is:”string1.lastIndexOf(“how”)) output: index is:24.

7.reverse()

let string1= [ “hello”, ”buddy”, “how”, “are”, “you”];

reverse methods reverse the index of the element in the array.Note that it will change the original array.

console.log(string1.reverse()) output:you,are,how,buddy,hello.

8.push(),unshift()

let string1= [ ”buddy”, “how”, “are”];

This two methods are used to add value in array.push methods add value at the end of the array.unshift method are used to add beginning of the array.

string1.push(“you”); console.log(string1) //output: buddy,how,are,you. string1.unshift(“hello”); console.log(string1) //output:hello, buddy, how, are, you.

9.pop(),shift()

let string1= [ “hello”, ”buddy”, “how”, “are”, “you”];

pop method remove the last index of element in the array.shift remove the first index of the element of the array.

string1.pop(); console.log(string1) //output:hello, buddy,how,are string1.shift(); console.log(string1) //output: buddy, how, are, you.

10.sort()

let string1= [ “how”, “are”, “you”];

sort method will sort the array.sorting can be alphabetic or numeric also ascending or descending order.by default sort method will short as string alphabetic and ascending order.

string1.pop(); console.log(string1) //output: “are”, “how”, “you”

--

--