In this tutorial, we will learn how to split String into Substrings of N characters in JavaScript.
So to split string by length of N character in javascript, we will use the following methods
- Using String.split() and regex
- Using String.match() and regex
- Using substr()
Split a string by length of N characters using split()
The split()
method is used to split a string into an array of substrings and return us a new array.
To split a string into substrings with the length of N character, we will use the following regular expression /.{1, N}/g
.
var str = "123456"
const result = str.split(/(.{1,2})/g).filter(x => x)
console.log(result) // [ '12', '34', '56' ]
Here, we have used regex to split the string into a specific length of chunks/substring.
The / /
(forward slash) is the beginning and end of a regex expression.
The .
is used to find a single character in the string except the newline or line terminator.
The g
(global) flag is used to perform a global match. It finds all matches in the string rather than stopping after the first match.
The expression {1,2}
is used to tell the program the range, here at least 1 or at most 2 of the succeeding characters in the string.
The filter(x=>x)
is used to filter out empty elements which is created between chunks while using regex.
Read more about regular expression here : Regular expression syntax cheatsheet – JavaScript | MDN
Split String to Substring of N character using match()
const str = "123456".match(/.{1,2}/g);
console.log(str) //[ '12', '34', '56' ]
The String.match()
method is used to search a string for a match against a regular expression. If a match is found it will return it in an array.
If the match is not found, it will return null
.
We can create a reuasble function like this,
function splitString(str, length) {
return str.match(new RegExp('.{1,' + length + '}', 'g')) || [];
}
console.log(splitString('1450s',2)),2)) //[ '14', '50', 's' ]
Since match()
method returns null when a match is not found in the string. So we have used the ||
(logical OR) to return an empty array ([]
) instead of null .
If you don’t want to use regular expressions for this, we can use a loop with substr().
Split a String into a Substring using substr() method
We will use the for loop method to split the string into sub-string with the length of N character.
Example:
function splitStrings(str, n) {
const arr = [];
for (let index = 0; index < str.length; index += n) {
arr.push(str.substr(index, n));
}
return arr;
}
console.log(splitStrings('abcd1234ABCD8976', 4));
Output:
[ 'abcd', '1234', 'ABCD', '8976' ]
Here, we have a function with takes in two parameters, string and the length of the substring.
We have used for loop to iterate over the string with the increment of N to the index value.
And on each iteration, we have extracted the characters of N length from the string using substr()
method and push it into our empty array.
The substr()
method takes in two parameters and its syntax is
string.substr(start, length)
start : The start position from where we want to extract from the string.
length : The number of characters we want to extract.
Once the loop has extracted the characters from the string we return the array of substrings.
Conclusion: Using the split()
, match()
and, substr()
method, we can split a string into substrings of n characters easily in JavaScript. Regex can perform the task will one line of code, however, if you don’t like using regex, you can go for the for loop method.
Related Topics: