Javascript string methods
Created By: chatGPT
In JavaScript, strings are objects that represent text. They come with a variety of built-in methods that allow you to manipulate and retrieve information from string values. Here are some of the most commonly used string methods:
charAt(): Returns the character at the specified index of a string.
let str = 'Hello';
let char = str.charAt(1);
console.log(char); // 'e'
concat(): Combines two or more strings into one.
let str1 = 'Hello';
let str2 = ' World';
let result = str1.concat(str2);
console.log(result); // 'Hello World'
includes(): Checks whether a string contains a specified substring.
let str = 'Hello World';
let containsHello = str.includes('Hello');
console.log(containsHello); // true
indexOf(): Returns the first index at which a given substring can be found, or -1 if not found.
let str = 'Hello World';
let index = str.indexOf('World');
console.log(index); // 6
replace(): Returns a new string with some or all matches of a pattern replaced by a replacement.
let str = 'Hello World';
let newStr = str.replace('World', 'JavaScript');
console.log(newStr); // 'Hello JavaScript'
slice(): Extracts a section of a string and returns it as a new string without modifying the original string.
let str = 'Hello World';
let sliced = str.slice(0, 5);
console.log(sliced); // 'Hello'
toLowerCase(): Converts the entire string to lower case.
let str = 'Hello World';
let lowerStr = str.toLowerCase();
console.log(lowerStr); // 'hello world'
toUpperCase(): Converts the entire string to upper case.
let str = 'Hello World';
let upperStr = str.toUpperCase();
console.log(upperStr); // 'HELLO WORLD'
split(): Splits a string into an array of substrings based on a specified delimiter.
let str = 'Hello World';
let words = str.split(' ');
console.log(words); // ['Hello', 'World']
trim(): Removes whitespace from both ends of a string.
let str = ' Hello World ';
let trimmed = str.trim();
console.log(trimmed); // 'Hello World'