A string is a sequence of one or more characters that may consist of letters, numbers, or symbols. Strings in JavaScript are primitive data types and immutable, which means they are unchanging.
In JavaScript, strings are primitive data types, and they come with several methods and properties that allow you to manipulate, query, and transform them. Here's a comprehensive overview:
length
:
Description: Returns the number of characters in a string.
Example:
let str = "Hello, World!";
console.log(str.length); // Output: 13
charAt(index)
:
Description: Returns the character at a specified index.
Example:
let str = "Hello";
console.log(str.charAt(1)); // Output: "e"
charCodeAt(index)
:
Description: Returns the Unicode value (character code) of the character at the specified index.
Example:
let str = "Hello";
console.log(str.charCodeAt(1)); // Output: 101 (Unicode value of "e")
concat(str2, str3, ...)
:
Description: Combines multiple strings into one.
Example:
let str1 = "Hello";
let str2 = " World!";
console.log(str1.concat(str2)); // Output: "Hello World!"
includes(searchString)
:
Description: Returns true
if the string contains the specified substring, otherwise false
.
Example:
let str = "Hello, World!";
console.log(str.includes("World")); // Output: true
indexOf(searchString)
:
Description: Returns the first index at which the specified substring is found, or 1
if not found.
Example:
let str = "Hello, World!";
console.log(str.indexOf("World")); // Output: 7
replace(searchValue, newValue)
:
Description: Replaces the first occurrence of a substring with a new substring.
Example:
let str = "Hello, World!";
console.log(str.replace("World", "JavaScript")); // Output: "Hello, JavaScript!"
slice(start, end)
:
Description: Extracts a portion of a string from the start
index up to (but not including) the end
index.
Example:
let str = "Hello, World!";
console.log(str.slice(7, 12)); // Output: "World"
split(separator)
:
Description: Splits a string into an array of substrings based on the specified separator.
Example:
let str = "apple,banana,orange";
let fruits = str.split(",");
console.log(fruits); // Output: ["apple", "banana", "orange"]
toLowerCase()
:
Description: Converts all characters in the string to lowercase.
Example:
let str = "HELLO";
console.log(str.toLowerCase()); // Output: "hello"
toUpperCase()
:
Description: Converts all characters in the string to uppercase.
Example:
let str = "hello";
console.log(str.toUpperCase()); // Output: "HELLO"
trim()
:
Description: Removes whitespace from both ends of the string.
Example:
let str = " Hello, World! ";
console.log(str.trim()); // Output: "Hello, World!"
startsWith(searchString)
:
Description: Checks if the string starts with the specified substring, returns true
or false
.
Example:
let str = "Hello, World!";
console.log(str.startsWith("Hello")); // Output: true