Arrangement of Digits within a String

I need a regex that can capture strings in groups of three, but if the remaining characters are not divisible by three, I want them grouped in twos.

For example:

  • 123456 should be 123 456
  • 1234567891011 should be 123 456 789 10 11

Could someone please assist me with this?

I attempted (.{1,3})(.{3}|.{2}) but it didn't work as expected.

Answer №1

You may want to consider using a positive lookahead for two characters.

const modify = text => text.replace(/.{2,3}(?=..)/g, '$& ')

console.log(['12', '123', '1234', '12345', '123456', '1234567', '12345678', '123456789', '1234567890'].map(modify));

Answer №2

Give this a shot:

(?=\d{5})(\d{3})|(\d{2})

https://regex101.com/r/qrpF4T/1

Breakdown:

  1. (?=\d{5}) - positive lookahead, matches if there are exactly 5 digits remaining at the end of the string.
  2. (?=\d{5})(\d{3}) - when there are five digits left at the end of the string, group them into sets of three numbers.
  3. |(\d{2}) otherwise, group them into sets of two numbers.

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

Identify and forward to the mobile-friendly version of the site

I am currently working on a website that requires separate files for mobile view as the html layout poses challenges in making it responsive. My goal is to find code that can detect if the user is accessing the site from a mobile device, and automatically ...

Tips on connecting input fields to a modal in AngularJS

My form is set up with a Customer and its properties populating input fields. When the user needs to change the Customer, they click on the CustomerName input which triggers a modal to open with a Customer List for selection. The chosen selection should th ...

An issue encountered with react-router-dom and the useLocation() function

Seeking guidance from experienced developers! I recently started using react-router-dom and encountered an issue with the useLocation() hook in my application. The error message states: "useLocation() may be used only in the context of a <Router> ...

Retrieve the div element from the webpage

I've scoured the internet in search of a suitable technique, but unfortunately, I haven't had much luck. Essentially, I am interested in using JavaScript or jQuery (potentially with Ajax) to extract a specific word from a div on a page within my ...

Issues with obtaining a reply

Encountering some issues while attempting to make an ajax call. The logic for this is stored in chat.js (included in the HTML head section) and it makes a request to getChatHistory.php chat.js: function retrieveChatData(user1, user2){ var response = &a ...

Mastering the art of using res.send() in Node.js

I have been working on a project using the mongoose API with Node.js/Express. There seems to be an issue with my get request on the client side as the data is not coming through. Can someone help me figure out what's wrong? Snippet of backend app.ge ...

What techniques can I use to streamline the following?

var cleanWord = word .split(/[^a-z0-9\s.\|]/gi) .join("") .replace(/([~@#$%^&*()_+=`{}\[\]\\:;<>\/ ])+/g, ""); I suspect that I am redundantly using the join function twice here. Is there a way to ...

Instructions on displaying the filename as the input for width and height dimensions

Running into an issue with Bootstrap 4 - whenever I try to upload a file with a long name, it ends up overflowing beyond the input field. ...

When IntelliJ starts Spring boot, resources folder assets are not served

I'm following a tutorial similar to this one. The setup involves a pom file that manages two modules, the frontend module and the backend module. Tools being used: IDE: Intellij, spring-boot, Vue.js I initialized the frontent module using vue init w ...

Steps to automatically set a selected item when the page is loaded for the first time

I am currently working on a test project using Angular where I have to choose a branch, and once selected, graphics will load with the specific information related to that branch. However, when the page initially loads, I encounter an issue where the selec ...

A step-by-step guide on how to repeatedly reload a nextJS page using recursion and display an error page once the

I've been experimenting with a recursive page reload function that looks like this: export const refreshPage = (count)=>{ if (count <= 0){ // window.location.reload(); console.log("blue"); return }else { console.log(& ...

Implement Dynamic Filters in a Vue Component

How can filters be programmatically applied to select values? During each iteration of records and columns, I am checking if the column ID starts with 'd', indicating it's a datetime field. In such cases, I want to apply the humanize filter ...

Angular throws an error when attempting to access a property that is undefined

I created the following angular template: <section class="section"> <div class="container"> <form [formGroup]="testForm"> <div class="columns is-multiline"> <div class="column is-2"> ...

eliminate the firebase firestore query using onSnapshot

Seeking assistance with the following code snippet: firebase.firestore() .collection("chatrooms") .doc(`${chatId}`) .collection(`${chatId}`) .orderBy("timestamp") .limit(50).onSnapshot((snapshot) => { //performing oper ...

Maximum size limitation for JSON parameters

Utilizing jQuery $.ajax json POST, I am accessing my WCF Web service. One of the input parameters is notably lengthy - exceeding 8000 bytes. It comprises a list of GUIDs separated by commas, such as "78dace54-1eea-4b31-8a43-dcd01e172d14,ce485e64-e7c6-4 ...

In React.js, it is required to enclose adjacent JSX elements within a parent tag

Help needed with JSX element wrapping in ReactJS What am I missing in my code?? Error message reads as follows: Adjacent JSX elements must be wrapped in an enclosing tag The issue lies within the element tags const renderTodos = currentTodos.map(( ...

Radio Button Fail to Work as Expected due to Missing Attribute

I've attempted various suggested solutions for this issue, such as using the required attribute on one input and setting it to "required." I'm currently unsure of the next steps to take. Any advice on resolving this problem would be greatly appre ...

Having trouble identifying the issue with the dependent select drop down in my Active Admin setup (Rails 3.2, Active Admin 1.0)

I am currently working on developing a Ruby on Rails application that involves three models: Games that can be categorized into a Sector (referred to as GameSector) and a subsector (known as GameSubsector) A sector consists of multiple subsectors. A Subs ...

Running a command line tool from a Node.js application: A step-by-step guide

My question pertains to running a command line tool from a node.js application, specifically one called tilemantle. In the documentation for tilemantle, it is suggested to install it globally and run it from the command line. However, I am interested in i ...

What is the proper way to utilize JQuery and Ajax to communicate with a global function in writing?

My goal is to retrieve data from an AJAX request and store it in a global variable. Despite trying to make the call synchronous, I am encountering issues where the value of the global variable becomes undefined outside of the Ajax request. I have attempt ...