JavaScript String methods and properties

JavaScript String methods and properties

Couple of string methods that i normally use.

ยท

2 min read

CharAt()

The charAt() method returns the character at the specified index in a string.

const string = "Hello"
console.log(string.chartAt(2) //Output: l

concat()

The concat() method combines two or more strings in a single string

const string1 = "Hello";
const string2 = "world";
const combined = string1.concat(string2)/
console.log(combined) //output: "Hello world

endsWith()

The endsWith() method checks if the string ends with the given string. Return boolean value

const string = "Hello world"
console.log(string.endsWith("world") //output: true

includes()

The includes() method checks if a string is included in another string. Returns boolean value.

const string1 = "Hello JavaScript";
const string2 = "JavaScript";
console.log(string1.includes(string2); //output: true

indexOf()

The indexOf() method returns the index of the first occurrence of a string in another string.

const string1 = "Hello world";
const string2 = "w";
console.log(string1.indexOf(string2); //output: 6

length

The length property returns the number of characters in a string.

const string = "Hello world";
console.log(string.length); //output: 11

trim()

The trim()returns a new string stripped of whitespace characters from beginning and end of a string

const string = " Hello ";
console.log(string.trim()); //output: "Hello"

split()

The split() method returns an array by checking the given condition.

const string = "hello, how are you";
console.log(string.split(" ") //output: ["hello," "how", "are", "you"]

slice()

The slice() method returns a substring of a string. The slice() method has two optional parameters start and end index.

const string = "hello"
console.log(string.slice(0,2);//output: "he"
ย