DEV Community

Cover image for JavaScript String Manipulation Techniques Every Developer Should Know
Rajeshwari Pandinagarajan for Syncfusion, Inc.

Posted on • Originally published at syncfusion.com on

JavaScript String Manipulation Techniques Every Developer Should Know

Strings play a vital role in any programming language. Properly understanding string manipulation techniques can help developers easily handle tricky situations.

In JavaScript, strings are immutable and help us to store text that includes characters, numbers, and Unicode. Also, JavaScript includes many built-in functions for creating and manipulating strings in various ways.

In this article, I will discuss the JavaScript string manipulation techniques every developer should know.

1. Split a string into a character array

As developers, we face many situations where we need to split strings into character arrays. For example, it is one of the most asked questions in software engineer interviews. In JavaScript, there are many ways to split a string into character arrays:

split()

The split() method divides a string into an ordered list of two or more substrings and returns it, depending on the pattern, divider, or delimiter provided.

let quote = 'I am Nipuni';

// Split string using the space character 

let array1 = quote.split(' '); 
console.log(array1); 
// ["I", "am", "Nipuni"] 

// Split string using an empty string (on each character)

let array2 = quote.split(''); 
console.log(array2); 
// ["I", " ", "a", "m", " ", "N", "i", "p", "u", "n", "i"]
Enter fullscreen mode Exit fullscreen mode

from()

The from() method of the Array class is the leading competitor for the split() method. It allows us to make an array from a data source. We can also use this to make an array from an iterable string.

let name = "Nipuni Arunodi";

// String to array of chracters 

let nameChars = Array.from(name); 
console.log(nameChar); 
// ["N","i","p","u","n","i"," ","A","r","u","n","o","d","i"]
Enter fullscreen mode Exit fullscreen mode

Spread operator (…)

The spread operator is another JavaScript feature that helps us to create an array from a string.

let name = "Nipuni Arunodi";

// Spread out string into an array 

let nameChar = [...name]; 
console.log(nameChar); 
// ["N","i","p","u","n","i"," ","A","r","u","n","o","d","i"]
Enter fullscreen mode Exit fullscreen mode

2. Check for a specific sequence in a string

Similar to splitting, there are many ways to check for a specific sequence in a JavaScript string. The includes() method, indexOf(), or a regular expression can be used for such purposes. However, includes() is the most frequently used method for determining whether a string contains a letter or series of letters. It was specifically created for that purpose.

const text = "Hi, My name is Nipuni"

console.log(text.includes("Nipuni")); 
// true

console.log(text.includes("Arunodi")); 
// false
Enter fullscreen mode Exit fullscreen mode

3. Check if a string starts or ends with a specific sequence

includes() checks for a specific sequence in an entire string. If you want to determine whether a string begins or ends with a specific substring, there are two specialized methods for that.

The string method startsWith() determines whether a string begins with a specific substring. It will return true if the string begins with the specified substring. Otherwise, it returns false.

const text = "Hi, My name is Nipuni"

console.log(text.startsWith("Hi")); // true
Enter fullscreen mode Exit fullscreen mode

The endsWith() method allows us to determine whether a string ends with a specified string.

const text = "Hi, My name is Nipuni"

console.log(text.endsWith("Hi")); // false
Enter fullscreen mode Exit fullscreen mode

4. Split a string on multiple separators

Initially, I mentioned that the split() function could be used to split a string into an array. Similarly, you can pass a regular expression into the split() function to split a string on multiple operators simultaneously.

// Split on comma (,) and semicolon (;).

const list = "Car,Bus;Train"

const vehicles= list.split(/[,;]/);
console.log(fruits); 
// ["Car", "Bus", "Train"]
Enter fullscreen mode Exit fullscreen mode

5. Reverse characters in a string

This is another regular question for entry-level developer interviews. There are numerous ways to reverse a string using JavaScript. For example, we can combine the split() method with the reverse() and join() methods.

With this approach, first, you need to split the string into an array using split(). Next, you reverse the array using reverse(), and then finally join it again using the join() function. This is the simplest way to reverse a string in JavaScript.

const word = "Nipuni";
const reversedWord = [...word].reverse().join("");

console.log(reversedWord); // "inupiN"
Enter fullscreen mode Exit fullscreen mode

6. Copy a string multiple times

repeat() is a string method in JavaScript that allows us to repeat a string a specified number of times. Since the repeat() method is a string object method, it must be used with a specific instance of the String class.

// Concatenate "0" 10 times.

const zeroString= "0".repeat(10);
console.log(zeroString); // "0000000000"
Enter fullscreen mode Exit fullscreen mode

7. Pad a string to a specific length

You may want your string to be a specified length at times. If your string is too short, you’ll want to fill in the gaps until it reaches the desired length. Previously, people often used libraries for this. Instead, you can now use the padStart() and padEnd() methods to pad your string at the beginning or end.

// Add 0 to the beginning until the string has a length of 10.
const string = "001".padStart(10, "0");
console.log(string); // "0000000001"

// Add * to the end until the string has a length of 10.
const string = "99".padEnd(10, "*");
console.log(string ); // "99 ********"
Enter fullscreen mode Exit fullscreen mode

8. Count characters in a string

You can easily use string.length method to get the length of a string. It will return the number of characters in the string.

const word = "Nipuni";
console.log(word.length); // 6
Enter fullscreen mode Exit fullscreen mode

9. Converting a letter in a string to uppercase or lowercase

You can use the toUpperCase() and toLowerCase() methods to convert a character of a string to uppercase or lowercase, respectively. For example, if you need to capitalize the first letter, you can use the following approaches:

// Method 1 - To Uppercase
let name = "nipuni";
name = name[0].toUpperCase() + name.substr(1);
console.log(name); // "Nipuni"

// Method 1 - To Lowercase
name = name[0].toLowerCase() + name.substr(1);
console.log(name); // "nipuni"

// Method 2 - To Uppercase
let name = "nipuni";
const characters = [...name];
characters[0] = characters[0].toUpperCase();
name = characters.join("");
console.log(name); // "Nipuni"

// Method 2 - To Lowercase
const characters = [...name];
characters[0] = characters[0].toLowerCase();
name = characters.join("");
console.log(name); // "Nipuni"
Enter fullscreen mode Exit fullscreen mode

10. Replace all occurrences of a string

There are several approaches to replacing all occurrences of a string. The replace() method or a regular expression with the global flag are some common approaches developers use.

However, JavaScript introduced a new method named replaceAll() in 2021 to replace all the occurrences at once. However, this new approach is not currently accessible in all browsers or the latest versions of Node.js.

const text = "I like Cars. Cars have 4 wheels"
console.log(text.replace(/Cars/g, "Vans"));
// "I like Vans. Vans have 4 wheels"

console.log(text.replaceAll("Cars", "Vans"));
// "I like Vans. Vans have 4 wheels"
Enter fullscreen mode Exit fullscreen mode

Conclusion

In almost every programming language, the string is one of the most basic data types. Developers need to deal with various string manipulations every day in their projects.

This article discussed some of the most common string manipulation techniques in JavaScript every developer should know. I hope this article helped you improve your knowledge. Thank you for reading.

Syncfusion’s Essential JS 2 is the only suite you will ever need to build an app. It contains over 65 high-performance, lightweight, modular, and responsive UI components in a single package. Download a free trial to evaluate the controls today.

If you have any questions or comments, you can contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!

Related blogs

Top comments (0)