javascript

Working with String


 

String is a primitive data types, but they also be treated as objects through the String Object. The String object provides additional properties and methods for working with strings. Here’s an overview.

 

Creating String Objects

 

Let's create a string bject using the String() constuctor.

let str = new String("LearnCoding!");

 

Properties

 

Length: It returns the length of the string.

console.log(str.length); // Outputs: 12

 

Methods

 

charAt(index):  It returns the character at the specified index.

console.log(str.charAt(0)); // Outputs: L

 

concat(string): It concatenates two or more strings and returns a new string.

let newStr = str.concat(" Welcome");
console.log(newStr); // Outputs: LearnCoding! Welcome

 

indexOf(substring): It returns the index within the calling String object of the first occurrence of the specified value.

console.log(str.indexOf("Welcome")); // 13

 

slice(start, end): It extracts a section of a string and returns it  as a new string.

console.log(str.slice(0, 5)); // Outputs: Learn

 

String objects are less commonly used compared to primitive strings because they have a slight overhead due to their object nature. Primitive strings are generally preferred for performance reasons