In this tutorial, you will learn about various string methods in JavaScript.
String Length
The length property provides the number of characters contained in a string.
let x = "WebmasterMaze";
console.log(x.length); // Output: 13Extracting String Characters
JavaScript provides several methods to extract characters from a string:
Using charAt()
The charAt() method retrieves the character located at a specified index (position) within a string.
var x = "WebmasterMaze";
console.log(x.charAt(4)); // Output: aUsing charCodeAt()
The charCodeAt() method in JavaScript returns the Unicode (UTF-16) code of the character at a specified index in a string. The returned value is an integer between 0 and 65535.
let x = "WebmasterMaze";
console.log(x.charCodeAt(0)); // Output: 87Using at()
Similar to charAt(), but supports negative indexing.
const name = "WebmasterMaze";
let letter = name.at(2);
console.log(letter); // Output: bUsing Bracket [] Notation
Simplest way to access a character. Does not support negative indexing.
const name = "WebmasterMaze";
let letter = name[2];
console.log(letter); // Output: bExtracting String Parts
JavaScript provides three methods for extracting parts of a string:
slice(start, end)
- Extracts a portion of a string and returns it as a new string.
- Supports negative indexes (counts from the end).
- The end index is exclusive (not included).
let text = "JavaScript Programming";
console.log(text.slice(0, 10)); // Output: "JavaScript"
console.log(text.slice(11)); // Output: "Programming" (Extracts from index 11 to the end)
console.log(text.slice(-11)); // Output: "Programming" (Negative index starts from the end)
console.log(text.slice(-11, -6)); // Output: "Progr"substring(start, end)
- Similar to
slice(), but does not support negative indexes. - If start > end, it swaps them automatically.
console.log(text.substring(0, 10)); // Output: "JavaScript"
console.log(text.substring(11)); // Output: "Programming"
console.log(text.substring(10, 0)); // Output: "JavaScript" (Swaps automatically)
console.log(text.substring(-5, 10)); // Output: "JavaScript" (Negative index is treated as 0)substr(start, length)
- Extracts a portion of a string based on length.
- Supports negative indexes for start.
- length defines how many characters to extract.
console.log(text.substr(0, 10)); // Output: "JavaScript"
console.log(text.substr(11, 5)); // Output: "Progr"
console.log(text.substr(-11, 5)); // Output: "Progr" (Starts from the 11th character from the end)Converting Strings to Uppercase and Lowercase
JavaScript provides built-in methods to convert a string to uppercase or lowercase easily:
toUpperCase()
This method returns a new string with all letters in uppercase.
let text = "Hello World";
console.log(text.toUpperCase()); // Output: "HELLO WORLD"- Works on both letters and mixed-case strings.
- Does not modify the original string (strings are immutable).
toLowerCase()
This method returns a new string with all letters in lowercase.
console.log(text.toLowerCase()); // Output: "hello world"- Useful for case-insensitive comparisons.
String concat() Method
The concat() method in JavaScript is used to join two or more strings and return a new combined string.
let firstName = "John";
let lastName = "Doe";
let fullName = firstName.concat(" ", lastName);
console.log(fullName); // Output: "John Doe"- It does not modify the original strings.
- You can concatenate multiple strings at once.
- Spaces must be added manually if needed.
- Use
+or template literals (${}) for simple concatenation. - Use
join()if you’re dealing with arrays. - Avoid
concat()unless necessary.
String trim()
The trim() method eliminates any leading and trailing whitespace from a string.
let text = " WebmasterMaze! ";
console.log(text.trim()); // Output: "WebmasterMaze!" (Removes spaces from both ends)
console.log(text.trimStart()); // Output: "WebmasterMaze! " (Removes spaces from the start)
console.log(text.trimEnd()); // Output: " WebmasterMaze!" (Removes spaces from the end)String Padding Method
JavaScript provides two methods for padding a string:
padStart(targetLength, padString)padEnd(targetLength, padString)
let text = "42";
console.log(text.padStart(5, "0")); // Output: "00042" (Pads with "0" at the start)
console.log(text.padEnd(6, "*")); // Output: "42****" (Pads with "*" at the end)
console.log("123".padStart(6, "AB")); // Output: "AB123" (Trims excess padding)
console.log("Hello".padEnd(10)); // Output: "Hello " (Pads with spaces by default)String repeat() Method
The repeat() method creates a new string by repeating the original string a specified number of times.
Syntax
string.repeat(count)- count: The number of times to repeat the string (must be ≥ 0).
- Returns a new string, does not modify the original.
- Throws an error if count is negative or Infinity.
let text = "Hello ";
console.log(text.repeat(3)); // Output: "Hello Hello Hello " (Repeats 3 times)
console.log("Hi".repeat(5)); // Output: "HiHiHiHiHi" (No spaces added automatically)
console.log("-".repeat(10)); // Output: "----------" (Useful for separators)
console.log("Test".repeat(0)); // Output: "" (Empty string if count is 0)
// Invalid cases
// console.log("Error".repeat(-1)); // Throws an errorReplacing String Content
JavaScript provides several ways to replace content within a string.
replace()
Replaces only the first occurrence of a specified value.
let text = "I love JavaScript. JavaScript is fun!";
console.log(text.replace("JavaScript", "PHP"));
// Output: "I love PHP. JavaScript is fun!"- Case-insensitive (use /pattern/
ifor case-insensitive replacement). - Can use regular expressions for more control.
replaceAll()
Replaces all occurrences of a specified value.
console.log(text.replaceAll("JavaScript", "PHP"));
// Output: "I love PHP. PHP is fun!"- Works with strings and regular expressions (/pattern/
g).
Using Regular Expressions (/pattern/g)
For replacing all occurrences dynamically:
console.log(text.replace(/JavaScript/g, "PHP"));
// Output: "I love PHP. PHP is fun!"/g(global) ensures all matches are replaced./i(case-insensitive) ignores letter case.
JavaScript split() Method
The split() method divides a string into an array based on a specified separator.
let text = "apple,banana,grape,orange";
// Split by comma
console.log(text.split(","));
// Output: ["apple", "banana", "grape", "orange"]
// Split by a character (e.g., "a")
console.log(text.split("a"));
// Output: ["", "pple,b", "n", "n", "gr", "pe,or", "nge"]
// Split into individual characters
console.log(text.split(""));
// Output: ["a", "p", "p", "l", "e", ",", "b", "a", "n", "a", "n", "a", ",", "g", "r", "a", "p", "e", ",", "o", "r", "a", "n", "g", "e"]
// Split with a limit (only first 2 elements)
console.log(text.split(",", 2));
// Output: ["apple", "banana"]
// Split by a space (useful for sentences)
let sentence = "Hello World! JavaScript is awesome.";
console.log(sentence.split(" "));
// Output: ["Hello", "World!", "JavaScript", "is", "awesome."]
// Split with no separator (returns entire string in an array)
console.log(text.split());
// Output: ["apple,banana,grape,orange"]