Performing double string splitting with multiple separators in javascript

If I have a string like a.b.c.d#.e.f.g.h#.i.j.k.l and want to split it first by "#" and then by ".":

str = a.b.c.d#.e.f.g.h#.i.j.k.l

res = str.split("#")

res[0] will contain a.b.c.d after the first split.
Now, I need to further split this data.

Is there anyone who can provide assistance with this?

Answer №1

One effective method to achieve this is by utilizing regex:

    var text = "a.b.c.d#.e.f.g.h#.i.j.k.l";

    var result = str.split(/[.#]/);

Answer №2

While this post may be dated, I stumbled upon it and believe there could be a more updated solution available. This method offers a cleaner approach to the problem at hand and provides greater flexibility. Utilizing the reduce prototype proves to be quite efficient in handling this task. Furthermore, it can easily be adjusted to generate an object with key/value pairs.

const input = 'a.b.c#.e.f.g#.h.i.j'
const firstDelimiter = '#';
const secondDelimiter = '.';

// Eliminate empty values within sub arrays
const cleanInput = input.replace(/#./g, '#');

// Split by the firstDelimiter
const output = cleanInput.split(firstDelimiter).reduce( (newArr, element, i) => {
  // At this stage, you will have an array like ['a.b.c', 'e.f.g', 'h.i.j']
  // Each element is passed into the callback as the 'element' variable
  let subArr = element.split(secondDelimiter); // split the element by the second delimiter, creating another array like ['a', 'b', 'c'], etc.
  console.log(i, newArr)
  // Accumulator newArr retains its values
  newArr[i] = subArr;

  return newArr;

}, []); // The initial value of the accumulator must be []

console.log('final:', output);

Answer №3

In my opinion, a straightforward way to divide a string using character a followed by character b is like this:

string.split('a').join('b').split('b')

Answer №4

To achieve the desired outcome of splitting a string by '#' and then further splitting each item by '.', follow the steps below:

Given Input:'a.b.c.d#.e.f.g.h#.i.j.k'

Expected Output:[ a b c d e f g h i j k]

var str = 'a.b.c.d#.e.f.g.h#.i.j.k.l';
        var resultArray = [];
        var splitByHash = str.split('#');
        for (var i = 0; i < splitByHash.length; i++) {
            var subSplit = splitByHash[i].split('.');
            for (var j = 0; j < subSplit.length; j++) {
                resultArray.push(subSplit[j]);
            }
        }
        alert(resultArray);

Answer №5

Check out this custom function I created to separate elements in an array:

function separateArray(arr, separator) {
    let resultArr = [];
    for(let i = 0; i < arr.length; i++) {
        arr[i] = arr[i].split(separator);
        arr[i].forEach(item => {
            resultArr.push(item);
        });
    };
        return resultArr;
};

You can use it in your scenario like so:

string = "a.b.c.d#.e.f.g.h#.i.j.k.l";
console.log( separateArray (string.split ("#"), "." ) );

Answer №6

To divide a string using multiple separators, you can utilize regular expressions:

str.split(/SEP_1|SEP_2|SEP_N/);

Ensure that SEP does not include any special characters used in regex, if it does, remember to precede them with '\'

Answer №7

If you need to split a string in JavaScript, you can utilize a function similar to PHP's explode.

//   example 1: explode(' ', 'Kevin van Zonneveld');
//   returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}

function explode(delimiter, string, limit) {
  //  discuss at: http://phpjs.org/functions/explode/
  // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)

  if (arguments.length < 2 || typeof delimiter === 'undefined' || typeof string === 'undefined') return null;
  if (delimiter === '' || delimiter === false || delimiter === null) return false;
  if (typeof delimiter === 'function' || typeof delimiter === 'object' || typeof string === 'function' || typeof string ===
    'object') {
    return {
      0: ''
    };
  }
  if (delimiter === true) delimiter = '1';

  // Here we go...
  delimiter += '';
  string += '';

  var s = string.split(delimiter);

  if (typeof limit === 'undefined') return s;

  // Support for limit
  if (limit === 0) limit = 1;

  // Positive limit
  if (limit > 0) {
    if (limit >= s.length) return s;
    return s.slice(0, limit - 1)
      .concat([s.slice(limit - 1)
        .join(delimiter)
      ]);
  }

  // Negative limit
  if (-limit >= s.length) return [];

  s.splice(s.length + limit);
  return s;
}

Discover more useful functions at

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

The implementation of CORS headers does not appear to function properly across Chrome, Firefox, and mobile browsers

I encountered an issue while trying to consume a third party's response. The functionality works correctly in Internet Explorer, but fails in Chrome, Firefox, and on my mobile browser. Despite searching online and testing various codes, I continue to ...

Trouble with jQuery addClass function when trying to add to a specific object variable

I'm attempting to give an error class to an input textbox to inform the user that their input is invalid. Within the change event, I am referencing what seems to be the input field and storing it in a variable. However, calling addClass on the var ...

Discovering ways to access deeply nested JSON data in Vue JS

i am dealing with JSON data that includes payment information. I am facing issues retrieving the paid_amount and date for both cash_payment and installment_payment. { "response": [ { "status": "sold", "price": "1000 ...

Spread the picture on social media using Progressive Web App

I am currently working on a Nuxt PWA where I have implemented a function to convert HTML to Canvas using a specific package. The output generated is in base 64 format. My goal now is to find a way to easily share this image through various platforms such a ...

Crafting redirect rules in React that avoid redirecting to the same route

In my project, there is a file named AuthenticatedRoute.tsx, which serves as a template for all the protected/authenticated routes in my Router.tsx file. export default ({ component: C, authUser: A, path: P, exact: E }: { component, authUser, path, ex ...

Is there a way to effectively communicate and pass state information between sibling components in React?

Is there a way to share state data between two React component functions that are both children of another component? I am new to React and have tried exporting a const from my App.jsx file with a structure containing the state properties, but when queri ...

Using the html5 file reader API in JavaScript to retrieve a file as a binary string and then sending it through an ajax request

I'm attempting to obtain the binary string of files, but I seem to be unable to do so. Why does readAsDataUrl work while readAsBinaryString doesn't? I have posted my code on jsbin and any help would be greatly appreciated. Thank you. Check out ...

Tips for combining or adding duplicated values in a Javascript array

I am facing a problem with an array object that looks like this: [ {"item_id":1,"name":"DOTA 2 Backpack","image":"XXX","qty":1,"original_price":1450000,"total_price":1450000}, {"item_id":2,"name":"Mobile Legend Backpack","image":"XXX","qty":1,"origin ...

What are the steps to start a project on a personal computer?

Utilized on   - Windows 7, 64-bit I am interested in exploring how the project functions with github.com - project. Query: How can I get the project to do this? Steps Taken:   1. Saved the project to the directory. c:\test\visualStudio ...

Efficiently parsing function arguments from arrays of known length in C++ using simdjson

I've been working with the simdjson library to parse nested lists within a json object provided by a third party. Unfortunately, I'm unable to modify the data structure. Here's a snippet of the code in question: #include <iostream> #i ...

Tips for creating a responsive layout to ensure that H2 achieves its optimal font size in a one-line DIV

Is there a way to ensure that an H2 headline fits within the width of a DIV element? I am looking for a solution where the font size of the H2 automatically adjusts to display its full text without overflowing or breaking into a second line inside the DIV ...

Retrieving properties from a selector's output function

My situation is similar to the scenario described in the accessing react props in selectors documentation. However, in my case, let's assume that the visibilityFilter is coming from the props. Is there a way to achieve something like the following? e ...

I need to fetch data from mongoDB by allowing the user to input a name into a search field, and then retrieve all documents that correspond to that search term

I am currently able to query the database by finding a specific key:value pair in the documents. However, I would like to enhance this functionality by allowing users to input their own search criteria as an argument in the function. Right now, I have hard ...

The issue of duplicated elements arises when Ajax is utilized within Django

Upon form submission, a Graph is generated using Plotly. Utilizing Ajax to submit the form without refreshing the page results in duplicating the form div on the screen. How can this issue be resolved? The code snippet below showcases my implementation wit ...

A custom JavaScript function designed to replicate Excel's functionality of dividing numbers by thousands

I've noticed a unique behavior in Excel where when a cell is in focus and you enter, for example, 1500.32, it displays as 1 500.32. However, once you click enter or move away from the cell, it changes to 1 500.32. I'm intrigued by how this works. ...

steps for linking a directive variable to a controller

Encountering an issue with 2-way binding in Angular where changes made to the input do not reflect in the controller. However, the initial value set by the controller does affect the directive. In the screenshot, a value was changed but vm.date still hold ...

Unable to load the node modules

In my development journey, I created an ASP.NET MVC project using Angular 2 in Visual Studio 2017 and set up node for package management. Here is a snippet from the package.json file: { "version": "1.0.0", "name": "asp.net", "private": true, ... ...

Steps for wrapping a class with a higher order component

Is it feasible to encapsulate a class component within a higher order component (HOC) that is also a class? import React, { Component } from "react"; import { View } from "react-native"; import { Toast } from "react-native-easy-toast"; const withToast = ...

Scrolling with React Event

I am attempting to create a scrollbar that only appears when I scroll within a particular area using React. I am utilizing debounce and useState in my implementation. The issue: When I reach the end of the scroll, the event continues to repeat indefinitel ...

Unable to connect to server using React-Native fetch. Localhost is not being used

I recently encountered an issue with my app where the fetch function used for user authentication stopped working. Despite not making any changes, the transition from React 0.27 to 0.28 seemed to have caused this problem. After scouring through numerous S ...