String as an array-like object

The alternative is to think of the string as an object resembling an array, where each character is represented by an integer index:

Example:

Javascript




let str ="w3wiki"
console.log(str[1]);


Output

e

Let us go through some examples to better understand the usage of strings:

An array of Strings: To create an array of strings you can simply type:

// Creating an array of strings: string1, string2, string3
let arrString=["string1","string2","string3"];

or

// Creating an array of strings: string1, string2, string3
let arrString=new Array("string1","string2","string3");

Now let us go through some examples to understand strings better:

Example 1: In this example, we are going to concatenate two strings. To concatenate, I have simply used the + operator.

Javascript




let a = "Hello ";
let b = "World";
 
// Concatenating strings a and b
console.log(a + b);


Output

Hello World

Example 2: In this example, I am going to find the index of the first occurrence of b in the string. To do that, I used the indexOf() method.

Javascript




let a = "abcdefgh";
 
// Finding the first index of the character 'b'
console.log(a.indexOf('b'));


Output

1

Example 3: In this example, we will get the substring of the string. For that purpose, I have used the substring() method.

Javascript




let a = "abcdefgh";
 
// Printing the substring between the indices 2 and 7
console.log(a.substring(2, 7));


Output

cdefg

Example 4: In this example, replacing a part of the string with another string is literal, and using the replace() method to accomplish this.

Javascript




let a = "Hello World";
 
let arrString = ["Geeks", "for", "Geeks"]
 
// Replacing the word 'World' with 'Geeks'
console.log(a.replace("World", arrString[0]));


Output

Hello Geeks

You can check out more string functions in javascript here.



String in JavaScript

String is used to representing the sequence of characters. They are made up of a list of characters, which is essentially just an “array of characters”. It can hold the data and manipulate the data which can be represented in the text form. We can perform different operations on strings like checking their length, also concatenate them by using +=, +, string operators.

Similar Reads

Creating Strings:

There are two ways to create a string in Javascript:...

Method 1: Using string literal

A string can be created just by initializing with a string literal. There are three ways to write a string literal:...

Method 2: Using string object

...

Character Access:

A string can also be created using a String object....

Method 1: Using charAt() Method

...

Method 2: String as an array-like object

A character can be accessed from a string in one of two ways....

Contact Us