Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (161).NET Core  (29).NET MAUI  (63)Angular  (74)ASP.NET  (50)ASP.NET Core  (79)ASP.NET MVC  (88)Azure  (36)Blazor  (152)DocIO  (23)Essential JS 2  (85)Essential Studio  (172)File Formats  (28)Flutter  (123)JavaScript  (186)Microsoft  (113)PDF  (67)React  (62)Succinctly series  (128)Syncfusion  (609)TypeScript  (31)Uno Platform  (3)UWP  (4)Vue  (39)Webinar  (35)Windows Forms  (59)WinUI  (52)WPF  (138)Xamarin  (155)XlsIO  (25)Other CategoriesBarcode  (5)BI  (29)Bold BI  (5)Build conference  (6)Business intelligence  (54)Button  (4)C#  (119)Chart  (57)Cloud  (12)Company  (445)Dashboard  (8)Data Science  (3)Data Validation  (6)DataGrid  (55)Development  (396)Doc  (7)DockingManager  (1)eBook  (96)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (23)Extensions  (18)File Manager  (4)Gantt  (11)Gauge  (11)Git  (4)Grid  (28)HTML  (10)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (311)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (30)Performance  (9)PHP  (1)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (7)Road Map  (10)Scheduler  (36)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (22)Solution Services  (3)Spreadsheet  (11)SQL  (8)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (11)Tips and Tricks  (92)UI  (224)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (23)Visual Studio Code  (17)Web  (373)What's new  (213)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Share on twitter
Share on facebook
Share on linkedin
JavaScript String Manipulation Techniques Every Developer Should Know

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

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

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

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

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

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

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

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"

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"

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

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

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"

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"

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 forumssupport portal, or feedback portal. We are always happy to assist you!

Related blogs

Tags:

Share this post:

Share on twitter
Share on facebook
Share on linkedin
Popular Now

Be the first to get updates

Subscribe RSS feed
Scroll To Top