In this article, we will see different ways to split a string based on the given length in javascript.

Using substring()

The substring() method returns the part of a string between the start and end indexes (Including), or a specified length. You can use this method to split a string by its length.

Here’s an example:

const str = 'HelloWorld';
const len = 3;
const result = [];

for (let i = 0; i < str.length; i += len) {
  result.push(str.substring(i, i + len));
}

console.log(result);
["Hel", "loW", "orl", "d"]

In the above example, we initialized the string str and the length len of the substring we want to create. We then looped through the string using for loop and extracted substrings using the substring() method. Finally, we pushed the substrings into the result array.

Using match()

By using the match() method, we can search for a match in a string using a regular expression and can return array of matches. We can use this method to split a string by its length.

Following is an example:

const str = 'HelloWorld';
const len = 3;
const result = str.match(new RegExp(`.{1,${len}}`, 'g'));

console.log(result);

output:

["Hel", "loW", "orl", "d"]

In the above example, we used a regular expression to match substrings of a specific length. The .{1,${len}} regex pattern matches any character between 1 and the specified length. The g flag enables the global search, which matches all occurrences in the string.

Using slice()

The slice() method extracts a section of a string and returns a new string. We can use this method to split a string by its length.

Following is an example:

const str = 'HelloWorld';
const len = 3;
const result = [];

for (let i = 0; i < str.length; i += len) {
  result.push(str.slice(i, i + len));
}

console.log(result);

output:

["Hel", "loW", "orl", "d"]

In the above example, we used a for loop to iterate through the string and extract substrings using the slice() method. We then pushed the substrings into the result array.

Categorized in:

Tagged in: