Dividing a string into three sections in JavaScript: A step-by-step guide

I want to use JavaScript to divide a string into three parts, regardless of the string's length. Each part can have a different number of characters.

For instance:

AABC:

  • part 1: AA
  • part 2: B
  • part 3: C

AABBC

  • part 1: AA
  • part 2: BB
  • part 3: C

aheuc

  • part 1: ah
  • part 2: eu
  • part 3: c

hello world

  • part 1: hell
  • part 2: o wo
  • part 3: rld

Answer №1

Here is a function that can help you achieve your desired output:

function divideStringIntoThreeEqualParts(string) {
  if (string.length <= 3) return string.split('');
  
  const remainder = string.length % 3;
  const divisor = Math.floor(string.length / 3);
  
  const separator1 = remainder === 2 || remainder === 1 ? 1 : 0;
  const separator2 = remainder === 1 || remainder === 0 ? 0 : 1;
  
  const part1 = string.slice(0, divisor + separator1);
  const part2 = string.slice(divisor + separator1, (divisor * 2) + separator1 + separator2);
  const part3 = string.slice((divisor * 2) + separator1 + separator2);
  
  return [part1, part2, part3];
}

Answer №2

If you're looking to easily divide a string into three parts, the following method will do just that.*

function splitIntoChunks(string) {
    var regex = RegExp(".{1,"+Math.ceil(string.length/3)+"}", 'g');
    return string.match(regex);
}

This code creates a regular expression function specifically designed to break down a string into chunks. The uniqueness here lies in determining chunk length based on dividing the overall string length by 3 (as indicated in the regex variable).

* However, it's important to note that this method works best for strings longer than 5 characters. Shorter strings may not be evenly divided into 3 chunks due to insufficient length.

Sample outputs include:

> splitIntoChunks("abcdefg");
  (3) ["abc", "def", "g"]

> splitIntoChunks("abcdefghijk");
  (3) ["abcd", "efgh", "ijk"]

> splitIntoChunks("abc");
  (3) ["a", "b", "c"]

> splitIntoChunks("abcd"); // :(
  (2) ["ab", "cd"]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An alternative to PHP's exec function in Node.js

I am interested in developing a piece of software using C (such as prime number factorization) and hosting it on my web server with Node.js. Following that, I would like to create an HTML document containing a form and a button. Upon clicking the button, ...

What is preventing me from successfully adding a new item from a CSV file into an array within a PHP while loop?

My goal is to create a JSON string by importing data from a CSV file using PHP and updating a specific field in a MySQL database with that information. The data I want to import consists of comments for posts that are already in the database. These commen ...

Exploring the Function Scope within ViewModel

I have been facing an issue while trying to call a function from my ViewModel within a foreach loop. It seems like the function goes out of scope as soon as I call it. Being new to JavaScript, I am struggling to understand why this is happening. Here is t ...

Using Cleave.js to hide the input field in an HTML form

I am currently implementing cleave.js on a website in order to create a mask that restricts input to only a 3-digit number. Here is the snippet of code I am using with cleave.js: <script> let number = new Cleave("#numberId", { ...

Sending a list via Ajax in Django

I recently executed an Ajax call successfully: $.ajax({ url:'/quespaper/intermediate_table', type:'GET', processData: false, data:{'url_link':url_link_copy,'updated ...

How can we rearrange the positions of three items in an array?

I am dealing with a function that returns an array of objects structured like this const allGreen = _.filter( sidebarLinks, side => !isServicePage(side.slug.current) ); https://i.stack.imgur.com/dR8FL.png I am attempting to rearrange the positions of ...

Guide on utilizing loader.load() function to load a compressed file in three.js - Instructions on loading filename.json.gz

I've already compressed a file into a .gz file and stored it in S3. You can find it here: However, when I attempt to load it in Three.js using loader.load("https://oic-accounts.s3.ap-south-1.amazonaws.com/3d-try-json-files/gzip/3.json.gz", ...

Shader material for border and overlay effects in THREE.js

Can a sphere in THREE.js be given a material shader to achieve a unique visual effect like the one shown here? (I'm specifically interested in replicating the border, glow, and streak on the red sphere.) https://i.sstatic.net/rjfkm.png If this is po ...

"Troubleshooting a bug: GetElementById function fails to find elements with hyphenated

When calling attr('id') on an immutable id attribute for an HTML element, my code runs smoothly when the id contains no hyphens. However, it encounters issues when the id includes a hyphen. $('.coloursContainer .radio-box').live(' ...

Enter the variable into the parameter

I'm working with some Javascript code: document.getElementById("Grid").style.gridTemplateRows = "repeat(3, 2fr)"; I'm trying to insert a variable as an argument to modify my CSS style. When I attempt the following: "repe ...

Item 'unreachable' displayed in Firefox console

I am working with several divs that have the class='class_name'. I have also defined var A = document.getElementsByClassName('class_name'); console.log(A[0]); Upon checking in the Chrome console, it displays: <div class="class_n ...

Experiencing some unusual shadows in my Three.js project while attempting to add a simple shadow effect to a cube or group of cubes

Trying my hand at implementing shadows in Three.js, even though I am fairly new to JavaScript. My attempts to create a cube with a proper shadow have yielded partial results, as only a portion of the mesh seems to be casting the shadow. https://i.sstatic. ...

Easy ways to manipulate the style of array components in Vue.js

Hey there all you programmers, I'm reaching out to see if any of you have insight on how I can modify the style of a specific component within an Object array. This is the code snippet: <template> <div> <ul> <li v-fo ...

When the Protractor configuration is executed, it displays the message "The requested webpage cannot be accessed."

Testing protractor on a vanilla.js app and encountering an error when running protractor basicConf.js The following error is occurring: This webpage is not available ERR_CONNECTION_REFUSED Here is the test script in use: describe('foo', fun ...

Separating text for tooltips from the element itself

I'm looking to enhance my website by adding tooltip descriptions to elements based on their CSS classes. While tooltips are usually added using the element's title attribute, I have numerous elements with the same lengthy description and want to ...

Pressing "Enter" initiates the submission of the form

My webpage contains a stylish GIF displayed as a button within a div. The script inside the div triggers a click event when the ENTER key is pressed, using $(this).click(). This click action has its own functionality. Everything functions smoothly in Fire ...

The custom error page in NextJS is failing to display

In my custom pages/404.ts file, I have coded the following: export default function NotFound() { return <h1>404 - Page Not Found</h1> } Additionally, there is another page that displays a 404 error when the organization is null: import Error ...

transforming text into numeric form in the C language

Having trouble converting a string to a double. Seeking assistance. This is the code: char Price[100]; double newPrice; printf("\nPlease enter the price:"); fgets(Price, 100, stdin); newPrice = atof(Price); printf("\nPrice of item is %f", newPr ...

Instructions for adding transitions to an entire page in material-ui while maintaining a fixed AppBar

Is there a way to ensure that the material-ui AppBar remains fixed at the top while being wrapped with page contents in a transition? I want the AppBar to transition (e.g. Zoom or Slide) along with the rest of the page contents. I encountered this issue w ...

Bizarre String Behavior in jQuery JSON Through Ajax Request

Something unusual is occurring: whenever I try to send the string "??" to the server using AJAX $.ajax({ type: 'POST', url: path, dataType: 'json', data: JSON.stringify({ text: "??" }) }); it consistently results in send ...