In JavaScript, strings are a primitive data type and come with a variety of built-in methods that allow you to manipulate and work with strings. Here are some of the most common string methods in JavaScript:
length: This method returns the length of a string.
var myString = "Hello, World!";
console.log(myString.length); // Outputs 13
charAt(): This method returns the character at a specified index in a string.
var myString = "Hello, World!";
console.log(myString.charAt(1)); // Outputs "e"
substring(): This method returns a substring of a string, starting at a specified index and ending at a specified index.
var myString = "Hello, World!";
console.log(myString.substring(0, 5)); // Outputs "Hello"
indexOf(): This method returns the index of the first occurrence of a specified substring in a string.
var myString = "Hello, World!";
console.log(myString.indexOf("World")); // Outputs 7
toUpperCase() and toLowerCase(): These methods convert a string to all uppercase or lowercase letters.
var myString = "Hello, World!";
console.log(myString.toUpperCase()); // Outputs "HELLO, WORLD!"
console.log(myString.toLowerCase()); // Outputs "hello, world!"
split(): This method splits a string into an array of substrings based on a specified separator.
var myString = "Hello, World!";
console.log(myString.split(" ")); // Outputs ["Hello,", "World!"]
replace(): This method replaces a specified substring with another substring in a string.
var myString = "Hello, World!";
console.log(myString.replace("World", "Universe")); // Outputs "Hello, Universe!"
In addition to these methods, there are many other string methods available in JavaScript. Understanding how to use these methods can be very helpful in manipulating and working with strings in your JavaScript code.