A string is a sequence of characters used to represent text in programming. In JavaScript, strings are enclosed in either 'single quotes', "double quotes", or `template literals`.
let message = "Hello, world!";
let name = 'Rohan';
let greeting = `Hello, ${name}`;
lengthReturns the number of characters in a string.
let str = "Hello";
console.log(str.length); // 5
toUpperCase() / toLowerCase()Converts a string to upper or lower case.
let city = "delhi";
console.log(city.toUpperCase()); // "DELHI"
includes()Checks if a substring is present in a string. Returns true or false.
let email = "user@example.com";
console.log(email.includes("@")); // true
indexOf()Returns the index of the first occurrence of a specified value.
let text = "JavaScript";
console.log(text.indexOf("S")); // 4
slice(start, end)Extracts a section of a string and returns it as a new string.
let lang = "JavaScript";
console.log(lang.slice(0, 4)); // "Java"
replace()Replaces a value with another in a string.
let text = "I like HTML";
console.log(text.replace("HTML", "JavaScript")); // "I like JavaScript"
trim()Removes whitespace from both ends of a string.
let name = " Rohan ";
console.log(name.trim()); // "Rohan"
split()Splits a string into an array of substrings.
let fruits = "apple,banana,grape";
console.log(fruits.split(",")); // ["apple", "banana", "grape"]
charAt()Returns the character at a specified index.
let str = "Rohan";
console.log(str.charAt(2)); // "p"
concat()Joins two or more strings.
let fname = "Rohan";
let lname = "Kumar";
console.log(fname.concat(" ", lname)); // "Rohan Kumar"