Using a regular expression to divide a string while ensuring that double tokens are avoided

When splitting a string into an array using JavaScript, delimiters play a crucial role. If there are repeated delimiters, it indicates sub-values within the array. For example:

abc+!+;def+!+!+;123+!+;xyz

should be split into abc, [def, 123], xyz.

I've tried numerous variations and ended up with ((?:+!(?!+!))+\;|$), which may have been my initial attempt. After spending a lot of time on this, I seem to have hit a roadblock. I looked into resources like regex to parse string with escaped characters, but couldn't find a solution that fits my specific issue.

I'm sure someone out there is more knowledgeable in regular expressions than I am and I hope they can provide a solution.

Answer №1

After experimenting with different methods, I managed to achieve success by utilizing the .split() function along with a specific pattern found in this reference:

\b\+!\+;\b

Following that initial step, I proceeded to implement the following:

\b\+!\+!\+;\b

This process was repeated as needed. To fully automate this procedure, it is advisable to convert it into a recursive function. If you require assistance in creating one, I have constructed a basic JSFiddle to help get you started. Firstly, we divide the string using our original expression. Subsequently, we modify the expression by appending !\+ (this can be achieved dynamically). Consequently, we iterate through the initial array, check for matches with the new expression, and if found, further split the string.

var string = 'abc+!+;def+!+!+;123+!+;xyz',
    data = string.split(/\b\+!\+;\b/);

var regex = /\b\+!\+!\+;\b/
for(var i = 0; i < data.length; i++) {
    var string = data[i];

    if(string.match(regex)) {
        data[i] = string.split(regex);
    }
}

console.log(data);
// ["abc", ["def", "123"], "xyz"]

The implementation of transforming this into a recursive function has been left to the discretion of OP. Should you require additional guidance in this matter, feel free to reach out for more detailed explanations.

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

Pattern matching regular expressions to identify the most extended string of consecutive vowels

I've been able to successfully locate the first instance of vowel(s) with my code below, for instance with 'ua', but now I need to modify the regex to: 1) search the entire string before stopping at the first match, and 2) after completing s ...

ngFor filter for converting strings to lowercase

In my application, I am implementing a pipes example that converts uppercase strings to lowercase. For example, 'Activities' becomes 'activities'. The data is in Array format, and I am using this filter with *ngFor. However, I am encoun ...

Automatically populate a dropdown menu with options based on the user's birth date

I successfully managed to populate the drop-down fields for months, days, and years. Furthermore, I was able to calculate the age of the user; however, I have restricted it to a maximum of 13 years. Check out the code snippet below: $('#reg-yr' ...

discovering final instance with boost::string library

Is there a way to achieve the same functionality using boost libraries? int idx = md.filepath.lastIndexOf('/'); md.title = md.filepath.right(md.filepath.length() - idx -1); md.title = md ...

Defining data types for an array of objects in a useState hook

I'm having trouble understanding the issue with my code. interface dataHistory { data: string, before: string | number, after: string | number, } I have an interface defined outside of the Functional Component and inside I specify its struct ...

Creating an HTML table on-the-fly leads to the opening of a fresh new webpage

Has anyone encountered this issue before? I have a math table coding function, which runs when a button is clicked. However, when I click the button, the table appears on a new page instead of on the same page. <!doctype html> <html> <h ...

Elements within HTML are not recognized by external JavaScript files

I've come across a perplexing issue while coding in JavaScript, and despite searching online, I can't seem to find a solution. Basically, I have created an HTML document and linked it to an external JS file. However, when I try to reference an e ...

Filtering an array dynamically by utilizing an array of conditions

Can jQuery-QueryBuilder be used to filter an array? This amazing plugin generates a unique array of conditions: condition:"AND" rules: { field:"name" id:"name" input:"select" operator:"equal" type:"string" value:"Albert" } I have ...

Trigger a specific drop-down menu to appear upon selection of a radio button using AngularJS

Let me start by presenting my problem, accompanied by a simple piece of code: <body> <div> <input type="radio" name="salary"/>Per Year <select> <option value="0">All</option> ...

Process the ajax request upon clicking the link

There is a link on my webpage. <a href="tel:+1111" id="tel">+1111</a> I am trying to track every click in a database. Here is the AJAX code I have written: <script type="text/javascript"> $('#tel').on('click&apo ...

Optional subscripting for arrays in Swift allows for safe and concise

Here is a simple playground code snippet: var array :[Int?] array = [1, 2, 3] array![1] = 4 Encountered an error while running the Playground Playground execution failed: error: :8:1: error: '@lvalue $T6' is not identical to 'Int?' ...

Extract only numbers using regular expressions

I have a column in my table called pnum_s I want to retrieve only the rows where the value in the pnum_s column contains exactly 10 digits and no other characters What query should I use for this? This is what I've tried: SELECT * FROM mytable WHER ...

"Mongodb and mongomapper are powerful database tools often used

I am currently working on a Rails app that uses ActiveRecord to manage products. Each product has a category and subcategory, with each subcategory defined by multiple fields within the application. This system has become quite complex and I have been cons ...

Swap the < symbol with &gt; and & with &amp; within a specific node or location in an XML document

Hello everyone, I have a XML file with a node named Section, where certain characters like & and < are treated as invalid. I need to replace < with &lt; and & with &amp; only within the Section Node. Currently, I am using the following Java ...

Breaking down an object's data in a React component

I need to figure out how to properly extract variables and props from this code snippet: const MyComponent = (props, {data}) => { return ( <div data-set={props["data-set"]}> {data.name} </div> ) }; ...

Step-by-step guide on validating a user in Joomla using AJAX and jQuery

Is there a way to authenticate a user in Joomla through an AJAX call? I want to implement an error effect if the login is incorrect and redirect the user upon successful authentication. I am specifically interested in using JQuery's .ajax API for thi ...

Exploring JqueryUI tab navigation with the help of the <a> tag

I have come across several articles mentioning the possibility of navigating JqueryUI tabs using a button or anchor tag. Here is the method I am currently using: $("#vtabs").tabs(); $("#tabsinner").tabs(); $(".changeTab").click(function() { alert("as ...

Is it achievable to utilize HTML tabindex for activating a function?

Currently working on an application using PhoneGap, where I encounter a complex form layout. The form consists of a text input field at the top, followed by multiple buttons and additional text inputs below. I am wondering if it is feasible to activate a ...

Error: The function replace cannot be used on elem

Here is what I am attempting to achieve: for loop inside the append is not working Below is my code: $('body').append( $('<section>').append( $('<form>') .attr('class', "ac-custom a ...

Ajax request yields an empty result

I have a very basic HTML page that includes some PHP and jQuery functionality <script type="text/javascript"> $(document).ready(function() { $.ajax({ url: "test.php", type: "POST", ...