JavaScript String Methods

Facebook logoTwitter logoLinkedin logo
image contains "JavaScript String Methods" text and vectors

JavaScript is a versatile programming language that allows developers to manipulate and work with text data effectively. One of the key components of text manipulation in JavaScript is the use of string methods.

These methods enable you to perform a wide range of operations on strings, from basic tasks like finding and replacing substrings to more complex operations like regular expression matching.

In this guide, we will explore some of the most commonly used JavaScript string methods and how to leverage them in your projects.

JavaScript String Methods

Let's start with the basics. The length property of a string returns the number of characters in the string. It's a property, not a method, but it's fundamental when dealing with strings.

const myString = "Hello, World!";
const length = myString.length; // Returns 13
Copy

charAt() Method

The charAt() method allows you to retrieve the character at a specified position within a string. It takes an index as an argument and returns the character at that position. Keep in mind that JavaScript uses a zero-based index, meaning the first character is at index 0.

const text = "Hello, World!";
const firstChar = text.charAt(0); // "H"
const fifthChar = text.charAt(4); // "o"

console.log(firstChar);
console.log(fifthChar);
Copy

charCodeAt() Method

The charCodeAt() method in JavaScript is used to retrieve the Unicode value (UTF-16 code unit) of a character at a specified index within a string. It takes an index as an argument and returns an integer representing the Unicode value of the character at that index.

const str = "Hello, World!";
const index = 0; // Index of the character 'H'

const charCode = str.charCodeAt(index);

console.log(`The Unicode value of character at index ${index} is ${charCode}`);
Copy

In this example, we have a string "Hello, World!" and we use charCodeAt(0) to get the Unicode value of the character at index 0, which is 'H'. The result will be 72, which is the Unicode value for 'H'.

concat() Method

The concat() method in JavaScript is used to concatenate, or join together, two or more strings and create a new string. It does not modify the original strings but instead returns a new string that is the result of joining the original strings in the order they were provided as arguments.

const str1 = 'Hello, ';
const str2 = 'world!';
const result = str1.concat(str2);

console.log(result); // Output: Hello, world!
Copy

In this example, we have two strings, str1 and str2. We use the concat() method to concatenate them together, resulting in the new string "Hello, world!".

startsWith() Method

The startsWith() method allows you to check if a string starts with a specified substring. It returns true if the string starts with the given substring; otherwise, it returns false. Here are some code examples to illustrate how to use the startsWith() method:

const str = "Hello, world!";
const prefix = "Hello";

console.log(str.startsWith(prefix)); // true
Copy

endsWith() Method

The endsWith() method in JavaScript is used to determine whether a string ends with a specified substring. It returns true if the string ends with the given substring; otherwise, it returns false. Here's an example of the endsWith() method:

const str1 = 'Hello, world!';
const str2 = 'Welcome to JavaScript';

// Example 1: Using endsWith() without specifying length
console.log(str1.endsWith('world!')); // true
console.log(str2.endsWith('world!')); // false

// Example 2: Using endsWith() with length
console.log(str1.endsWith('Hello', 5)); // true (considers the first 5 characters)
console.log(str2.endsWith('to', 10)); // true (considers the first 10 characters)

// Example 3: Case-sensitive comparison
console.log(str1.endsWith('World!')); // false (case-sensitive)
console.log(str2.endsWith('JavaScript')); // true

// Example 4: Checking for an empty string
console.log(''.endsWith('')); // true
Copy

In these examples, we use the endsWith() method to check if the given strings end with specific substrings or within specific character lengths. Keep in mind that the method is case-sensitive, so it considers the case of the characters when making comparisons.

includes() Method

The includes() method in JavaScript is a built-in method for strings and arrays that allows you to check if a given value exists within the string or array. It returns true if the value is found and false if it is not found. Here are some code examples demonstrating how to use includes() with strings:

const str = 'Hello, world!';
const searchString = 'world';

// Check if the string contains the substring
const containsSubstring = str.includes(searchString);

console.log(containsSubstring); // true
Copy

indexOf() Method

The indexOf() method in JavaScript is used to search for a specified substring or character within a string and returns the position (index) of the first occurrence of the substring or character. If the substring or character is not found, it returns -1.

const str = 'Hello, world!';
const index = str.indexOf('world');
console.log(index); // Output: 7 (the first 'w' in 'world' starts at index 7)
Copy

trim() & trimStrat() & trimEnd() Methods

trim() and trimStart() and trimEnd(). These methods remove leading and trailing whitespace (spaces, tabs, line breaks) from a string. Here's how you can use them with code examples:

trim(): Removes leading and trailing whitespace from a string.

const text = "  Hello, world!  ";
const trimmedText = text.trim();
console.log(trimmedText); // Output: "Hello, world!"
Copy

trimStart(): Removes leading whitespace from a string.

const text = "  Hello, world!";
const trimmedStartText = text.trimStart();
console.log(trimmedStartText); // Output: "Hello, world!"
Copy

trimEnd(): Removes trailing whitespace from a string.

const text = "Hello, world!  ";
const trimmedEndText = text.trimEnd();
console.log(trimmedEndText); // Output: "Hello, world!"
Copy

substring() Method

The substring() method in JavaScript is used to extract a portion of a string based on specified start and end indices and returns the extracted substring as a new string. Here's an example:

let originalString = "Hello, World!";
let substring1 = originalString.substring(0, 5); // Extracts from index 0 to 4
console.log(substring1); // Output: "Hello"

let substring2 = originalString.substring(7, 12); // Extracts from index 7 to 11
console.log(substring2); // Output: "World"

let substring3 = originalString.substring(3); // Extracts from index 3 to the end of the string
console.log(substring3); // Output: "lo, World!"
Copy

split() Method

The split() method is used to split a string into an array of substrings based on a specified delimiter. It takes the delimiter as an argument and returns an array of substrings. Here are some code examples to demonstrate how to use the split() method:

Example 1: Splitting a String into an Array

const sentence = "This is a sample sentence";
const words = sentence.split(" "); // Split the sentence into an array of words
console.log(words); // Output: ["This", "is", "a", "sample", "sentence"]
Copy

Example 2: Splitting with a Different Delimiter

const date = "2023-09-04";
const parts = date.split("-"); // Split the date string using "-" as the delimiter
console.log(parts); // Output: ["2023", "09", "04"]
Copy

Example 3: Splitting with Limit

You can also limit the number of splits using the optional second argument. In this example, we'll limit the splits to 2:

const sentence = "This is a sample sentence";
const words = sentence.split(" ", 2); // Limit the splits to 2
console.log(words); // Output: ["This", "is"]
Copy

Example 4: Splitting with Regular Expression

You can use regular expressions as delimiters for more complex splitting. Here's an example that splits a string using a regular expression to match spaces or commas:

const text = "Hello, World; JavaScript is fun";
const tokens = text.split(/[ ,;]/); // Split using a regular expression matching space, comma, or semicolon
console.log(tokens); // Output: ["Hello", "", "World", "", "JavaScript", "is", "fun"]
Copy

toString() Method

In JavaScript, the toString() method is a built-in method that you can use on various data types, including numbers, objects, arrays, and functions, to convert them into a string representation. Here are some code examples demonstrating the use of the toString() method with different data types:

1. Using toString() with Numbers:

let num = 42;
let numString = num.toString();

console.log(numString); // Outputs: "42"
Copy

2. Using toString() with Arrays:

let fruits = ["apple", "banana", "cherry"];
let fruitsString = fruits.toString();

console.log(fruitsString); // Outputs: "apple,banana,cherry"
Copy

3. Using toString() with Objects:

let person = {
  firstName: "John",
  lastName: "Doe",
};

let personString = person.toString();

console.log(personString); // Outputs: "[object Object]"
Copy

Note that when you use toString() on an object, it typically returns "[object Object]" by default. To get a custom string representation of an object, you can override the toString() method for that object.

4. Using toString() with Functions:

function greet(name) {
  return "Hello, " + name + "!";
}

let greetString = greet.toString();

console.log(greetString);
// Outputs the source code of the function:
// "function greet(name) {
//    return "Hello, " + name + "!";
//  }"
Copy

padStart() Method

The padStart() method is used to pad the current string with a specified string until it reaches a given length. This method is commonly used to format strings, such as adding leading zeros to a number or creating fixed-width columns of text. Here's an example of the padStart() method:

const number = 42;
const paddedNumber = number.toString().padStart(5, '0'); // Pad to a length of 5 with leading zeros
console.log(paddedNumber); // Output: "00042"
Copy

padEnd() Method

The padEnd() method is used to pad the current string with a given string until it reaches a specified length. This is often useful when you want to ensure that a string has a minimum length, and you want to fill the remaining characters with a specific padding string. Here's an example of the padEnd() method:

const str = "Hello";
const paddedStr = str.padEnd(10, "-");

console.log(paddedStr); // Output: "Hello-----"
Copy

The toLowerCase() and toUpperCase() Methods

In JavaScript, the toLowerCase() and toUpperCase() methods are used to convert strings to lowercase and uppercase, respectively. Here are explanations and code examples for each of these methods:

toLowerCase(): This method converts all characters in a string to lowercase.

let originalString = "Hello, World!";
let lowercaseString = originalString.toLowerCase();

console.log(lowercaseString); // Output: "hello, world!"
Copy

toUpperCase(): This method converts all characters in a string to uppercase.

let originalString = "Hello, World!";
let uppercaseString = originalString.toUpperCase();

console.log(uppercaseString); // Output: "HELLO, WORLD!"
Copy

repeat() Method

The `repeat()` method is used to create and return a new string by repeating the original string a specified number of times. It takes an integer argument that specifies how many times the string should be repeated. Here's the example

const originalString = "Hello, ";
const repeatedString = originalString.repeat(3);

console.log(repeatedString); // Outputs: "Hello, Hello, Hello, "
Copy

replace() Method

The replace() method in JavaScript is used to replace a specified substring or regular expression pattern in a string with another string.

1. Replace a single occurrence of a substring:

const originalString = 'Hello, World!';
const replacedString = originalString.replace('World', 'Universe');
console.log(replacedString); // Output: 'Hello, Universe!'
Copy

2. Replace all occurrences of a substring using a regular expression:

const originalString = 'This is an example. Example is good.';
const replacedString = originalString.replace(/example/gi, 'sample');
console.log(replacedString); // Output: 'This is an sample. Sample is good.'
Copy

3. Use a function as the replacement value:

function customReplace(match, p1, p2, offset, originalString) {
  // `match` is the matched substring
  // `p1`, `p2`, ... are capture group values if you use regular expressions with capture groups
  // `offset` is the position of the match within the original string
  // `originalString` is the original string
  return 'Replaced';
}

const originalString = 'Replace this and that.';
const replacedString = originalString.replace(/(this|that)/g, customReplace);
console.log(replacedString); // Output: 'Replace Replaced and Replaced.'
Copy

In this example, we use a custom function (customReplace) as the replacement value. This function is called for each match, and you can customize the replacement logic based on the match, capture groups, position, and original string.

The replace() method does not modify the original string; instead, it returns a new string with the replacements. If you want to modify the original string in place, you can assign the result back to the original variable:

let originalString = 'Hello, World!';
originalString = originalString.replace('World', 'Universe');
console.log(originalString); // Output: 'Hello, Universe!'
Copy

search() Method

The search() method is used to search for a specified pattern in a string and returns the position of the first occurrence of the pattern. It's often used with regular expressions to perform string searching. Here's how the search() method works with some code examples:

Searching for a Substring:

const text = "Hello, world! This is a simple example.";
const searchTerm = "world";

const position = text.search(searchTerm);

if (position !== -1) {
  console.log(`Found "${searchTerm}" at position ${position}.`);
} else {
  console.log(`"${searchTerm}" not found.`);
}
Copy

Using a Regular Expression:

const text = "The quick brown fox jumps over the lazy dog.";
const regex = /brown/i; // Case-insensitive search for "brown"

const position = text.search(regex);

if (position !== -1) {
  console.log(`Found "brown" at position ${position}.`);
} else {
  console.log(`"brown" not found.`);
}
Copy

Handling No Match:

const text = "This is an example string.";
const searchTerm = "banana";

const position = text.search(searchTerm);

if (position !== -1) {
  console.log(`Found "${searchTerm}" at position ${position}.`);
} else {
  console.log(`"${searchTerm}" not found.`);
}
Copy

Conclusion

Remember, practice makes perfect. Try out these methods in different scenarios and experiment with them to become proficient in string manipulation in JavaScript. Happy coding!