Guide for utilizing regex to divide a string by various characters in the expression?

Apologies if the wording is unclear. I am currently looking for a solution on how to include a string match of multiple characters in my dynamic regex expression.

The regex within my else statement successfully handles a single character input, now I am attempting to achieve the same functionality with multiple characters when passed into the initial if statement.

const delimiter = str.slice(0, str.indexOf('\n'));
  const strLength = delimiter.length;
  if (delimiter[0] === '[' && delimiter.charAt(strLength - 1) === ']') {
    const customDelimiter = delimiter.slice(delimiter.indexOf(delimiter[1]), delimiter.indexOf(delimiter.charAt(strLength - 1)));
    console.log(customDelimiter) // => '***'
    const regex = new RegExp(`,|\\n|\\${customDelimiter}`,'g');
    return strArr = str.split(regex).filter(Boolean);
  } else {
    const firstChar = str.slice(0, 1); // => '*'
    const regex = new RegExp(`,|\\n|\\${firstChar}`,'g');
    return strArr = str.split(regex).filter(Boolean);
  }

For instance, I desire for this specific string: '[*]\n11***22***33' to result in 66 due to splitting it into an array of [11, 22, 33] utilizing the '*' delimiter. However, an error message appears stating: "SyntaxError: Invalid regular expression: /,|\n|***/: Nothing to repeat".

Answer №1

Utilizing * as the delimiter in your regex transforms it into ,|\\n|\\|\*, which is the correct regex pattern. This pattern matches ',' or '\n' or a '*' character. In the context of your string, it matches [***]\n11***22***33.

However, if you use *** as the delimiter in your regex, it becomes ,|\\n|\\|\***, which is incorrect. In this scenario, two unescaped * characters appear together at the end. The presence of consecutive * symbols is problematic since in regex, '*' signifies zero or more occurrences of the preceding element, making its usage twice invalid.

This situation is unique due to the special interpretation of * within regex expressions. Using a non-regex character would have yielded the desired outcome.

An easier approach involves leveraging the javascript split function to achieve the intended result effortlessly. Firstly, split the string by using \n.

let splitStr = str.split('\n');
// This operation results in ["[***]", "11***22***33"]

Then proceed to split the content of index 1 from the splitStr array based on the specified delimiter.

splitStr[1].split('***');
// splitStr[1].split(customDelimiter)
// This action yields ["11", "22", "33"]

By adopting this methodology, there is no necessity to incorporate if/else statements for distinguishing between single character delimiters and multi-character delimiters.

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

Stopping Angular Route Alteration Depending on Routing Conditions

I have been searching everywhere for a solution to this issue. My goal is to be able to access the routing parameters collection and prevent the route from loading if a certain parameter is missing. I have tried using preventDefault in $routeChangeStart, b ...

Working with a Mix of Properties in Styled Components

Incorporating a button component with material design using styled-components is my current task. This component will possess various props including size, icon, floating, etc. However, managing the numerous combinations of props has become quite overwhel ...

HTML stops a paragraph when encountering a script within the code

Everything in my code is working correctly except for herb2 and herb3, which are not displaying or utilizing the randomizer. I am relatively new to coding and unsure of how to troubleshoot this issue. <!DOCTYPE html> <html> <body> ...

The addition of the URL # fragment feature to Safari's browser caching system

Currently, I am focused on improving the speed of our website. To achieve this, the client is utilizing ajax to preload the expected next page of the application: $.ajax({url: '/some/real/path', ...}); Upon receiving a response from the server ...

Picking out specific SharePoint components using jQuery

I encountered an issue with making my two radio boxes readonly. To resolve this, I attempted to disable the unchecked option. Despite trying to access the elements using jQuery and reviewing the data from the console, the solution did not work as expected. ...

Real estate listing featuring unique symbols

How do I include the ' character in properties when writing my object, like this: const championsList = { Kha'Zi: '...', }; Any suggestions on how to achieve this? ...

componentWillReceiveProps with excessive conditional statements

Having recently ventured into React development, I've already worked on 3 major projects utilizing React+Redux. However, I've noticed a recurring pattern that I find quite displeasing: componentWillReceiveProps(nextProps) { if (nextProps.par ...

Modifying an array without altering the reference

Perhaps my approach is not quite right, so please provide feedback if necessary! Imagine having an Array that represents some valuable data. var initial = ['x', 'y']; var duplicate = initial; initial.push('z'); console.log(i ...

Challenges in retrieving information from a two-dimensional JSON dataset

I am encountering an issue with a nested JSON structure. JSON: [{"id":"15", "rand_key":"", "landlord_name":"Shah", "property_req_1":{ "lead_req_id":"", "lead_id":"0", "category_id":"1", "region_id":"1", "area_location_id":"17", ...

Combine the initial element of one array with the initial element of another array in JavaScript

Is there a more efficient way to concatenate the first item of one array with the first item of another array in JavaScript, and automate console.log for each pair? Check out the code snippet below: $("button#search").on("click", function(){ var inputVa ...

Is there a way to trigger an Ajax function after individually selecting each checkbox in a list in MVC 4 using Razor syntax?

Is it possible to trigger an AJAX function when a checkbox within the ul below is checked? Each checkbox has a unique name attribute, such as chkbrand_1, chkbrand_2, chkbrand_3, etc. I am able to obtain the correct value using this code: $('.sear ...

PowerShell is having trouble detecting the Application during the packaging process

After completing the coding for a beginner Desktop Application in electron, I encountered an issue when trying to package it into an executable .exe file. The error message displayed was: Command failed: powershell.exe -nologo -noprofile -command "& { ...

"Utilizing jQuery's AJAX POST method with PHP is successful, while using XMLHttpRequest is not yielding

Currently in the process of revamping my existing code to transition from jQuery's AJAX function to using XMLHttpRequest in vanilla JS. My understanding is that the following code snippets should be equivalent. However, while the jQuery version functi ...

Choose the current div using JavaScript

Looking to add the selected product along with its quantity and price to another div tag using the jQuery click function. Each time I click, only the first array value of the variable "product" is displayed. How can I access the values of the current row ...

Iterating through the startPrivateConversation method in Botkit for a multitude of users

In order to send an update to all my users, I created a new bot controller in a separate js file. To achieve this successfully, I needed to implement a notification function inside the controller's rtm_open function. The goal was to iterate through th ...

Making a page jump with Javascript

Welcome! Let's dive into our question. Below you'll find my script and HTML code: My Script: const resultEl = document.querySelector('.allquotes'); const pageSize = document.querySelector('select[name="page-size"]') ...

Vue js: Automatically assign alternate text to images that are not found

Currently, I am in the process of developing a website that features a variety of products, each with its own unique image. For binding the image URL to the source attribute, I use the following code snippet: <img :src="product.ImageUrl"/> In case ...

After exiting the PWA, the IOS camera displays a black screen

I have implemented an HTML file input to open the camera and capture photos for my Progressive Web App (PWA). <input type="file" accept="image/*" capture="camera" name="photo" id="photo-input-js" data-project-id="<?php echo $projectId ?>"> // ...

Using JavaScript, redirect to a specified URL once a valid password has been entered on an HTML form

Need help with JavaScript for password validation and URL redirection. I'm new to JS and used some resources like Password correct? then redirect & Adding an onclick function to go to url in javascript?. Here's my current code: ...

The functionality to display dynamic images in Vue.js appears to be malfunctioning

As a newcomer to vue.js, I am facing a challenge in dynamically displaying images. Manually changing the images works fine, but I'm running into issues with dynamic display. I've come across similar problems online, but none of the solutions seem ...