What is the method for dividing a string using capital letters as a delimiter?

I am currently faced with the challenge of splitting a string based on capital letters. Here is the code I have come up with:

let s = 'OzievRQ7O37SB5qG3eLB';
var res = s.split(/(?=[A-Z])/)
console.log(res);

However, there is an additional requirement that complicates things. If the capital letters are continuous, the regex should continue "eating" until the sequence ends. In the provided example, it returns:

..R,Q7,O37,S,B5q,G3e,L,B

The desired result should actually be:

RQ7,O37,SB5q,G3e,LB

Any thoughts or suggestions would be greatly appreciated. Thank you.

Answer №1

In order to properly match these sections, use the regular expression /[A-Z]+[^A-Z]*|[^A-Z]+/g instead of splitting based on a zero-width assertion pattern. This is because the latter method (specifically using a positive lookahead-only regex in this scenario) requires checking every position within the string and cannot be instructed to skip a position once the lookaround pattern is identified.

s = 'and some text hereOzievRQ7O37SB5qG3eLB';
console.log(s.match(/[A-Z]+[^A-Z]*|[^A-Z]+/g));

Take a look at the online demonstration of this regex on regex101.com.

Particulars:

  • [A-Z]+ - denoting one or more uppercase ASCII characters
  • [^A-Z]* - allowing for zero or more non-uppercase ASCII character matches to accommodate uppercase-only segments
  • | - or
  • [^A-Z]+ - representing one or more non-uppercase ASCII characters to facilitate matching non-uppercase characters at the beginning of the string

The global modifier g will permit String#match() to return all discovered non-overlapping matches.

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

What is the reason behind only the final input value being shown on the screen?

I'm encountering an issue with my input fields. I have a total of five input fields. After filling all of them and clicking the button to display them on the screen, only the last one I entered is shown in all places... (let me know if this explanatio ...

Unable to Get Basic jQuery .load Example to Function

Seeking assistance with a jQuery issue regarding loading HTML snippets into a page. When the snippet contains just HTML, it loads fine. However, when it includes a script, there seems to be an issue. Simplified code provided below for better understandin ...

Proceed with executing the function only if the current date is before the specified date

I've created a countdown timer that can count both up and down from a given date. However, I want the countdown to only run in reverse and stop once it reaches the current date or any future dates. Currently, the alert message shows when the date is r ...

Scroll horizontally on a webpage using drag with JavaScript

I have been working on a unique horizontal website design that allows users to scroll horizontally by dragging the screen. I managed to successfully implement the horizontal scrolling feature, but I am facing difficulties in adding the horizontal drag-to-s ...

Ensure that the interface limits the key value to match precisely the value of a constant in Typescript

Seeking assistance in understanding how to enforce a specific type for an optional key within an interface: const FIRST = "FIRST" const SECOND = "SECOND" interface TSomeInterface { element: Element order?: typeof FIRST | typeof ...

"Enhancing JqGrid functionality with inline editing and custom formatters

I'm currently working with a column model that looks like this: { name: 'CostShare', index: 'CostShare', width: 50, formatter: 'number', formatoptions: { decimalPlaces: 2, suffix: "%" }, resizeable: true, align: 'ce ...

Looking to develop a dynamic JSON preview feature using AngularJS

Below is an example of JSON data: data: [{ test: { innertest: "2345", outertest: "abcd" }, trans: { sig: "sou", trip: [{ one: "2" }, { two: "3" }], otherac: "iii" },{ test: { innertest: "uuu", ...

Creating an MPG4 Video from a Three.js Scene: What Are the Steps?

I am working with a three.js scene that includes numerous animated objects. I am looking to export this animation as an mpg4 video. Here are my questions: What is the best method for exporting a scene to create an mpg4 video? Is it recommended to perfo ...

How can you generate a Base64 string with Node.js?

I recently utilized the html2pdf npm package to generate a base64 string of a PDF file and then sent it to my Node.js server. I used Nodemailer to send this PDF as an email attachment by configuring the mailOptions object like so: let mailOptions ...

Make the checkbox font-weight bold when it is checked

Attempting to apply custom CSS to enhance the appearance of checkboxes using input and label elements. The goal is to make the font-weight bold when a user clicks on the checkbox, and then revert it back to regular if clicked again. Currently stuck on this ...

Shifting the data label on a pie chart in ApexCharts - what's the trick?

I need help adjusting my data labels to make them more readable by moving them inward. It would be perfect if there is a way to dynamically center them within the slice. https://i.stack.imgur.com/bCelP.png Despite reading the documentation and trying dif ...

lengthy conditional statement in JavaScript

Is there a more efficient way to handle a long series of if-else statements in JavaScript? I'm not experienced enough with the language to optimize this code. Any suggestions or guidance would be greatly appreciated. $('#webform-component-primar ...

Error encountered when trying to send form data through an AJAX request

Whenever a user updates their profile picture, I need to initiate an ajax call. The ajax call is functioning properly, but the issue lies in nothing being sent to the server. <form action="#" enctype='multipart/form-data' id="avatar-upload-fo ...

"Upon refreshing the browser, an Angular map loses its positioning and appears blank

I have implemented a LeafLet map in my Laravel 9 system, which is functioning properly with some exceptions. Here's how it looks like: https://i.stack.imgur.com/kcuVr.jpg The code in the controller (CompetitionsMapController.php) is as follows: ...

Clear the cache of a query in React Query without having to fetch it again

Within my React app, I have implemented React Query in the following manner: const { data, status } = useQuery(key, queryFunc, { staleTime: 1 * 60 * 1000 }); In order to invalidate a specific key in the cache based on the value of the data, specifical ...

JavaScript - Combine objects by summing values with matching keys

Below is the given array : [ { "Date": "2019.07.08", "Organisation": "A", "Client": "Client1", "Product": "Pen", "Quantity": "1120" }, { "Date": "2019.07.08", "Organisation": "A", "Client": "Client1", "Product": " ...

When the application is converted into static files, the dynamic routes fail to function properly

I have a website that is statically exported but has dynamic routes. During development, the site works fine. However, when I build and export it, then serve the static files using serve, an issue arises. If you go to the site root and click on a link th ...

Utilizing react-query and next.js to pre-fetch initial data and automatically re-fetch when a filter is modified

In my NextJs project, I am attempting to prefetch data using react-query. The initial data should only be updated if the filter is modified. To manage the filter states, I have implemented State Hooks. function JobSearch(props) { const [pageNumber, setPa ...

Only allow scrolling if the number of child elements exceeds a certain limit

I am looking to implement a scroll feature on the <ul> element when the number of <li>s exceeds a certain threshold. For example, if we have 12 children, I want to display only 7 of them and then scroll through the rest. This is my current app ...

How can you use jQuery to activate a specific tab?

I have 3 tabs with 3 different ids. $(document).ready(function() { $(function() { $( "#tabs" ).tabs(); }); $("#links > a").click(function() { var link = $(this).attr('href').substr(-1,1); console.log(link); $('#t ...