Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Find Word Character in a String with JavaScript RegExp
Next article icon

How To Split a String Into Segments Of n Characters in JavaScript?

Last Updated : 16 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

When working with JavaScript, you might encounter a situation where you need to break a string into smaller segments of equal lengths. This could be useful when formatting a serial number, creating chunks of data for processing, or splitting a long string into manageable pieces.

In this article, we will explore various ways to split a string into segments of n characters using JavaScript.

Suppose you have a string "JavaScriptIsFun" and you want to split it into segments of 4 characters. The result would be an array like this:

["Java", "Scri", "ptIs", "Fun"]

This is what it means to split a string into segments of n characters. In this case, the string was divided into parts of 4 characters each.

Splitting a string into segments of n characters in JavaScript can be done in the following ways:

Table of Content

  • Using a for Loop
  • Using the match Method with Regular Expressions
  • Using the slice Method in a while Loop
  • Using the reduce Method
  • Using the split Method with a Loop
  • Using Array.from with a Mapping Function

1. Using a for Loop

The for loop approach is simple and easy to understand. It involves iterating through the string in steps of n characters and extracting each segment.

Syntax

for (let i = 0; i < str.length; i += n) {
// Logic to slice and store substrings
}

Example: In this example, we will split a string into segments of a specified length using a for loop, store the segments in an array, and return the array of segments.

JavaScript
function splitStringUsingForLoop(str, n) {     let segments = [];     for (let i = 0; i < str.length; i += n) {         segments.push(str.slice(i, i + n));     }     return segments; }  let str = "JavaScriptIsFun"; let result = splitStringUsingForLoop(str, 4); console.log(result); 

Output

["Java", "Scri", "ptIs", "Fun"]

2. Using the match Method with Regular Expressions

The match method can be adopted in conjunction with a regular expression to bisect the string into parts of n characters long. It is simple and employs the use of regular expressions More information about regular expressions can be found Here.

Syntax

str.match(new RegExp('.{1,' + n + '}', 'g'));

Example: In this example, we will split a string into segments of a specified length using the match() method with a regular expression, and return the array of segments.

JavaScript
function splitStringUsingMatch(str, n) {     return str.match(new RegExp(".{1," + n + "}", "g")); }  let str = "This is another sample string."; let result = splitStringUsingMatch(str, 4); console.log(result); 

Output

[ "This", " is ", "anot", "her ", "samp", "le s", "trin", "g." ]

3. Using the slice Method in a while Loop

Another method is to use while loop together with the slice in its implementation. This method is as good as the for loop, but where it is different from the for loop is how the iteration can be handled.

Syntax

while (i < str.length) {
// Logic to slice and store substrings
}

Example: In this example, we will split a string into segments of a specified length using a while loop, store the segments in an array, and return the array of segments.

JavaScript
function splitStringUsingWhileLoop(str, n) {     let segments = [];     let i = 0;     while (i < str.length) {         segments.push(str.slice(i, i + n));         i += n;     }     return segments; }  let str = "Splitting strings can be fun!"; let result = splitStringUsingWhileLoop(str, 3); console.log(result); 

Output

["Spl", "itt", "ing", " st", "rin", "gs ", "can", " be", " fun", "!"]

4. Using the reduce Method

The reduce method can also be used to invogue a string into segments of n characters. It is a common functional programming style and is stellar while taking advantage of the JavaScript’s array methods.

Syntax

str.split('').reduce((acc, char, index) => {
// Logic to accumulate substrings
}, []);

Example: In this example, we will split a string into segments of a specified length using the reduce() method, store the segments in an array, and return the array of segments.

JavaScript
function splitStringUsingReduce(str, n) {     return str.split('').reduce((acc, char, index) => {         if (index % n === 0) acc.push('');         acc[acc.length - 1] += char;         return acc;     }, []); }  let str = "JavaScript is powerful!"; let result = splitStringUsingReduce(str, 2); console.log(result); 

Output

["Ja", "va", "Sc", "ri", "pt", " i", "s ", "po", "we", "rf", "ul", "!"]

5. Using the split Method with a Loop

split method combined with reduce to split a string into segments of n characters. This approach involves first converting the string into an array of characters and then using the reduce method to group these characters into fixed-size chunks.

Syntax

str.split('').reduce((acc, char, index) => {
if (index % n === 0) acc.push('');
acc[acc.length - 1] += char;
return acc;
},[]);

Example: In this example, we will split a string into segments of a specified length using the split() method in combination with the reduce() method. The segments will be stored in an array, and the array of segments will be returned.

JavaScript
function splitStringUsingSplit(str, n) {     return str.split('').reduce((acc, char, index) => {         if (index % n === 0) acc.push('');         acc[acc.length - 1] += char;         return acc;     }, []); }  let str = "SplittingStringsInJavaScript"; let result = splitStringUsingSplit(str, 5); console.log(result); 

Output

["Split", "tingS", "tring", "sInJa", "vaScr", "ipt"]

6. Using Array.from with a Mapping Function

The Array.from method with a mapping function provides a clean way to split the string into segments.

Syntax

Array.from({ length: Math.ceil(str.length / n) }, (v, i) => str.slice(i * n, i * n + n));

Example: In this example, we will split a string into segments of a specified length using the Array.from() method, store the segments in an array, and return the array of segments.

JavaScript
function splitStringUsingArrayFrom(str, n) {     return Array.from({ length: Math.ceil(str.length / n) }, (v, i) => str.slice(i * n, i * n + n)); }  let str = "ExampleWithArrayFrom"; let result = splitStringUsingArrayFrom(str, 6); console.log(result); 

Output

["Exampl", "eWithA", "rrayFr", "om"]

Next Article
Find Word Character in a String with JavaScript RegExp
author
hadaa914
Improve
Article Tags :
  • JavaScript
  • Web Technologies

Similar Reads

  • How to Iterate Over Characters of a String in JavaScript ?
    There are several methods to iterate over characters of a string in JavaScript. 1. Using for LoopThe classic for loop is one of the most common ways to iterate over a string. Here, we loop through the string by indexing each character based on the string's length. Syntax for (statement 1 ; statement
    2 min read
  • Split a String into an Array of Words in JavaScript
    JavaScript allows us to split the string into an array of words using string manipulation techniques, such as using regular expressions or the split method. This results in an array where each element represents a word from the original string. 1. Using split() MethodUsing split() method with a chos
    5 min read
  • Find Word Character in a String with JavaScript RegExp
    Here are the different ways to find word characters in a string with JavaScript RegExp 1. Using \w to Find Word CharactersThe \w metacharacter in regular expressions matches any word character, which includes: A to Z (uppercase letters)a to z (lowercase letters)0 to 9 (digits)Underscore (_)You can u
    3 min read
  • JavaScript - Keep Only First N Characters in a String
    Here are the different methods to keep only the first N characters in a string 1. Using slice() MethodThe slice() method is one of the most common and efficient ways to extract a substring from a string. We can easily keep only the first N characters by passing 0 as the start index and N as the end
    3 min read
  • Remove a Character From String in JavaScript
    In JavaScript, a string is a group of characters. Strings are commonly used to store and manipulate text data in JavaScript programs, and removing certain characters is often needed for tasks like: Removing unwanted symbols or spaces.Keeping only the necessary characters.Formatting the text.Methods
    3 min read
  • How to create multi-line strings in JavaScript ?
    In JavaScript, the absence of native support for multi-line strings was a longstanding challenge. However, with the advent of ES6 (ECMAScript 2015), the things changed dramatically. ES6 introduced string literals, offering robust support for multi-line strings, which was a significant enhancement fo
    3 min read
  • JavaScript - How To Find Unique Characters of a String?
    Here are the various methods to find the unique characters of a string in JavaScript. 1. Using Set (Most Common)The Set object is one of the easiest and most efficient ways to find unique characters. It automatically removes duplicates. [GFGTABS] JavaScript const s1 = "javascript"; const s
    3 min read
  • JavaScript - Insert Character in JS String
    In JavaScript, characters can be inserted at the beginning, end, or any specific position in a string. JavaScript provides several methods to perform these operations efficiently. At the BeginningTo insert a character at the beginning of a string, you can use string concatenation or template literal
    2 min read
  • Add Minimum Characters at Front to Make String Palindrome in JavaScript
    The minimum characters to add at the front to make the string palindrome means the smallest count of characters required to prepend to the beginning of a given string. It ensures that the resultant string reads the same forwards and backward. This process creates a palindrome from the original strin
    5 min read
  • How to remove portion of a string after certain character in JavaScript ?
    Given a URL and the task is to remove a portion of URL after a certain character using JavaScript. split() method: This method is used to split a string into an array of substrings, and returns the new array. Syntax:string.split(separator, limit)Parameters:separator: It is optional parameter. It spe
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences