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]); |
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); |
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' )); |
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)); |
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])); |
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.
Contact Us