ESC

Search on this blog

Weekly updates

Join our newsletter!

Do not worry we don't spam!

String Manipulation in JavaScript with Code Examples


String manipulation is an essential skill for any JavaScript programmer. Whether you need to extract information from a string, convert letter case, concatenate strings, or remove extra whitespace, JavaScript provides a wide range of powerful methods and techniques to work with strings effectively. In this comprehensive guide, we'll explore various string manipulation techniques, complete with code examples, to help you master string manipulation in your JavaScript applications.

 

1. Extracting Characters from a String

JavaScript offers three primary methods for extracting individual characters from a string: charAt(), at(), and charCodeAt().

1.1. charAt(index)

The charAt() method takes an index as an argument and returns the character at that specific index within the string.

  const str = "Hello World!";
  console.log(str.charAt(0)); // Output: "H"
  console.log(str.charAt(8)); // Output: "r"
  console.log(str.charAt(16)); // Output: "" (empty string if index is out of range)
  

If the provided index is out of range, charAt() returns an empty string.

 

1.2. at(index)

Introduced in ES2022, the at() method is similar to charAt(). It accepts an index and returns the character at that index.

  const str = "Hello World!";
  console.log(str.at(0)); // Output: "H"
  console.log(str.at(8)); // Output: "r"
  console.log(str.at(16)); // Output: undefined (if index is out of range)
  

Unlike charAt(), at() returns undefined when the index is out of range. Additionally, at() supports negative indexing, allowing you to access characters from the end of the string.

  const str = "Hello World!";
  console.log(str.at(-1)); // Output: "!"
  console.log(str.at(-2)); // Output: "d"
  

1.3. charCodeAt(index)

The charCodeAt() method returns the UTF-16 code of the character at the specified index.

  const str = "Hello World!";
  console.log(str.charCodeAt(0)); // Output: 72
  console.log(str.charCodeAt(4)); // Output: 111
  

 

2. Extracting Substrings

JavaScript provides two main methods for extracting substrings from a string: substring() and slice().

2.1. substring(start, end)

The substring() method extracts a substring from the original string based on the provided start (inclusive) and end (exclusive) indexes.

  const str = "JavaScript";
  console.log(str.substring(0, 4)); // Output: "Java"
  

If the end index is omitted, substring() will extract the substring from the start index to the end of the string.

  const str = "JavaScript";
  console.log(str.substring(4)); // Output: "Script"
  

2.2. slice(start, end)

The slice() method is similar to substring(), extracting a substring based on the start and end indexes.

  const str = "JavaScript";
  console.log(str.slice(0, 4)); // Output: "Java"
  

Like substring(), the end index can be omitted to extract the substring from the start index to the end of the string.

  const str = "JavaScript";
  console.log(str.slice(4)); // Output: "Script"
  

The main difference between slice() and substring() is that slice() supports negative indexes, allowing you to extract substrings relative to the end of the string.

  const str = "JavaScript";
  console.log(str.slice(-10, -6)); // Output: "Java"
  

 

3. Converting Letter Case

JavaScript provides two methods for converting the letter case of a string: toUpperCase() and toLowerCase().

  const str = "JavaScript";
  console.log(str.toUpperCase()); // Output: "JAVASCRIPT"
  console.log(str.toLowerCase()); // Output: "javascript"
  

 

4. Concatenating Strings

There are multiple ways to concatenate strings in JavaScript:

4.1. Using the + operator:

  const str1 = "Hello";
  const str2 = "World!";
  const str3 = str1 + " " + str2;
  console.log(str3); // Output: "Hello World!"
  

4.2. Using the concat() method:

  const str1 = "Hello";
  const str2 = "World!";
  const str3 = str1.concat(" ", str2);
  console.log(str3); // Output: "Hello World!"
  

4.3. Using template literals (template strings):

  const str1 = "Hello";
  const str2 = "World!";
  const str3 = `${str1} ${str2}`;
  console.log(str3); // Output: "Hello World!"
  

 

5. Trimming Whitespace

JavaScript provides three methods for removing whitespace from the beginning and/or end of a string: trimStart(), trimEnd(), and trim().

 const str = " \n\tHello World!\t\n "; 
console.log(str.trimStart()); // Output: "Hello World!\t\n " 
console.log(str.trimEnd()); // Output: " \n\tHello World!" 
console.log(str.trim()); // Output: "Hello World!" 
  • trimStart() removes leading whitespace, including spaces, tabs, and line breaks.
  • trimEnd() removes trailing whitespace.
  • trim() removes whitespace from both ends of the string.

 

6. Adding Padding to Strings

The padStart() and padEnd() methods allow you to add padding characters or substrings to the beginning or end of a string.

 const str = "123"; console.log(str.padStart(5, "0")); // Output: "00123"
 console.log(str.padEnd(5, "0")); // Output: "12300" 

Both methods take two arguments: the target length of the resulting string and the substring to be used for padding. If the provided substring exceeds the target length, only a portion of it will be used.


READ ALSO:


7. Repeating Strings

The repeat() method creates a new string by repeating the original string a specified number of times.

 const str = "123"; console.log(str.repeat(3)); // Output: "123123123" 

 

8. Splitting Strings into Arrays

The split() method splits a string into an array of substrings based on a specified separator.

 const url = "http://www.example.com/blog/example-article"; const arr = url.split("/"); console.log(arr); // Output: ["http:", "", "www.example.com", "blog", "example-article"] const slug = arr[4];
 console.log(slug); // Output: "example-article" 

This method is particularly useful when extracting information from URLs or parsing delimited data.

 

9. Searching within Strings

JavaScript provides several methods for searching within strings:

9.1. indexOf() and lastIndexOf()

  • indexOf() returns the index of the first occurrence of a specified character or substring.
  • lastIndexOf() returns the index of the last occurrence of a specified character or substring.
 const str = "Hello World"; 
console.log(str.indexOf("l")); // Output: 2 
console.log(str.lastIndexOf("l")); // Output: 9 

Both methods return -1 if the character or substring is not found.

9.2. includes()

The includes() method checks whether a string contains a specified character or substring and returns a boolean value.

 const str = "Hello World";
 console.log(str.includes("Hello")); // Output: true 
console.log(str.includes("hello")); // Output: false 

9.3. startsWith() and endsWith()

  • startsWith() checks whether a string starts with a specified character or substring.
  • endsWith() checks whether a string ends with a specified character or substring.
 const url = "https://www.example.com"; 
console.log(url.startsWith("https")); // Output: true
 console.log(url.endsWith(".com")); // Output: true 

 

10. Replacing Substrings

The replace() method allows you to replace a specified substring or a regular expression pattern with another substring.

 const str = "Hello World";
 const newStr = str.replace("World", "Universe"); 
console.log(newStr); // Output: "Hello Universe" 

By default, replace() only replaces the first occurrence of the specified substring. To replace all occurrences, you can use a regular expression with the global flag (/g).

 const str = "Hello World World"; const newStr = str.replace(/World/g, "Universe"); 
console.log(newStr); // Output: "Hello Universe Universe" 

 

Conclusion

String manipulation is a fundamental aspect of JavaScript programming. With the various methods and techniques covered in this guide, you now have the tools to extract information from strings, convert letter case, concatenate strings, remove extra whitespace, add padding, split strings into arrays, search within strings, and replace substrings.

By leveraging these string manipulation techniques, you can efficiently process and manipulate textual data in your JavaScript applications. Remember to explore the official JavaScript documentation for more details on each method and their supported parameters.

Happy coding!

FIFA 25: Release Date, New Features, Gameplay Enhancements, and What to Expect
Prev Article
FIFA 25: Release Date, New Features, Gameplay Enhancements, and What to Expect
Next Article
Mobile SEO Best Practices
Mobile SEO Best Practices

Related to this topic: