JavaScript String Manipulation Techniques Every Developer Should Know
Tags: javascript, webdev, beginners, coding
Published: 2022-10-17 04:25:56

---
title: JavaScript String Manipulation Techniques Every Developer Should Know
published: true
date: 2022-10-11 10:30:24 UTC
tags: javascript, webdev, beginners, coding
canonical_url: https://www.syncfusion.com/blogs/post/javascript-string-manipulation-techniques-every-developer-should-know.aspx
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pcahx8nnwwezhadwr13i.png
---

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.

```js
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"]
```

### 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.

```js
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"]
```

### Spread operator (…)

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

```js
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"]
```

## 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.

```js
const text = "Hi, My name is Nipuni"

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

console.log(text.includes("Arunodi")); 
// false
```

## 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.

```js
const text = "Hi, My name is Nipuni"

console.log(text.startsWith("Hi")); // true
```

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

```js
const text = "Hi, My name is Nipuni"

console.log(text.endsWith("Hi")); // false
```

## 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.

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

const list = "Car,Bus;Train"

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

## 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.

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

console.log(reversedWord); // "inupiN"
```

## 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.

```js
// Concatenate "0" 10 times.

const zeroString= "0".repeat(10);
console.log(zeroString); // "0000000000"
```

## 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.

```js
// 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 ********"
```

## 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.

```js
const word = "Nipuni";
console.log(word.length); // 6
```

## 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:

```js
// 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"
```

## 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.

```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"
```

## 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](https://www.syncfusion.com/javascript-ui-controls "Syncfusion Essential JS 2 UI Controls") 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](https://www.syncfusion.com/downloads/essential-js2 "Essential Studio for JavaScript Free Trial") to evaluate the controls today.

If you have any questions or comments, you can contact us through our [support forums](https://www.syncfusion.com/forums "Syncfusion Support Forums"), [support portal](https://support.syncfusion.com/ "Syncfusion Support Portal"), or [feedback portal](https://www.syncfusion.com/feedback/ "Syncfusion Feedback Portal"). We are always happy to assist you!

## Related blogs

- [Javascript Api Mocking Techniques](https://www.syncfusion.com/blogs/post/javascript-api-mocking-techniques.aspx "Blog: Javascript Api Mocking Techniques")
- [Optimize Next.Js App Bundle And Improve Its Performance](https://www.syncfusion.com/blogs/post/optimize-next-js-app-bundle-improve-its-performance.aspx "Blog: Optimize Next.Js App Bundle And Improve Its Performance")
- [Javascript Map Vs. Object](https://www.syncfusion.com/blogs/post/javascript-map-vs-object.aspx "Blog: Javascript Map Vs. Object")
- [Effectively Visualize A Large Number Of Markers Using Javascript Maps](https://www.syncfusion.com/blogs/post/visualize-a-large-number-of-markers-using-javascript-maps.aspx "Blog: Effectively Visualize A Large Number Of Markers Using Javascript Maps")
- [Building An Image Carousel In Javascript Is Now Easy!](https://www.syncfusion.com/blogs/post/building-an-image-carousel-in-javascript-is-now-easy.aspx "Blog: Building An Image Carousel In Javascript Is Now Easy!")