JavaScript: Splitting strings with multiple delimiters

Can I use a Java Script function to divide a string into multiple parts?

var string = "This is a test text, again, this is a testing text";

For instance, I can split the string using , like this: string.split(','); resulting in:

var string = ["This is a test text", "again", "this is a testing text"];

Now, I am interested in splitting the string based on specific parameters, so the string array would be:

var string = ["test text", "testing text"]

I am seeking a function that can extract all the sections of the string that start with test and end with text.

Answer №1

It seems you're asking for a solution, so here is a function I quickly put together in 2 minutes to address the scenario:

var string = "This is a test text, again, this is a testing text";

function customSplit(str_to_split, start_string, end_string) {
    var res = [];
    var start_index, end_index;

    for (i = 0; i <= str_to_split.length; i++) {
        start_index = str_to_split.toLowerCase().indexOf(start_string.toLowerCase(), i);
        if (i == start_index) {
            end_index = str_to_split.toLowerCase().indexOf(end_string.toLowerCase(), i);
            if (end_index >= 0) {
                res.push(str_to_split.substring(start_index, end_index + end_string.length));
            }
        }
    }

    return res;
}

console.log(customSplit(string, "test", "text"));

When used with the given sentence, it will return ["test text", "testing text"].

If this solution helps you, please let me know.

UPDATE

Addressed a specific issue with a certain input string. Remember, this code was written hastily in just a couple of minutes.

Answer №2

Implement a regular expression:

let sentence = "Here is a sample sentence for testing a regular expression";
console.log(sentence.match(/sample.+?for/g));

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

Implement a new aggregate function for tooltips in the Kendo chart

I am currently utilizing a kendo chart with a date x-axis. Each point on the graph corresponds to different dates, but the x-axis displays only a monthly view. To showcase the last data point for each month, I have implemented a custom aggregate function a ...

Do not allow navigation to another page until the form has been submitted

As part of my project, I have implemented a feature where new users are required to change their password upon logging into their account for the first time. For new users, the Change Password screen is displayed immediately after login. The menu options ...

Loading a div using Ajax within a frame

My php page includes a div that is supposed to be populated by an Ajax call. function showcopay() { var apa = document.getElementById("alert_id").value; $("#copay").load('show_copay.php?pid='+apa); } The parent page of the div used to be ...

What is the most efficient way to use jQuery to retrieve the count of tags associated with a variable

I am trying to filter my data retrieved from ajax using a function. Here is the initial code: var csvf = data.filter(function (el) { return ['TRUCK_CPX'].indexOf(el.TAG) >= 0 && ['CA5533'].indexOf(el.Chave) >= 0 }); Now ...

Javascript does not function on sections generated by ajax

I'm facing an issue with a JavaScript function not working on a dynamically generated part using AJAX. Here is the AJAX call: <script> $(window).on('scroll', function() { $("#preloadmore").show(); if ($(window).height() + $(window ...

Center alignment is not possible for the Div element

Problem Every time I attempt to implement the following code (outlined below), the div only appears centered when using width: 100px;. <div style="border: solid 1px black; width: 100px; height: 100px; background-color: blue; margin-left: auto; mar ...

Modifying deeply nested properties in Vue.js

Within my Vue.js application, I've created a method to update the src attribute of images whenever a file is chosen from a file input field. This method is triggered like so: <input type="file" accept=".jpg,.png" @change="updateSrc($event, 'p ...

Using AngularJS to bind radio buttons to ng-model

Here is a snippet of my HTML code where I attempted to bind the "formFriendsAll" scope to the ng-model. <form ng-submit="submitForm()" > <div class="col-sm-3"> <div class="form-group"> <label>Which Persons to show?< ...

Is there a straightforward way to upload a folder in a ReactJS application?

I am searching for a way to upload a folder in ReactJS. I have a folder with .doc and .docx files in it, and I want the user to be able to upload the entire folder when they click the browse button. I need to prevent the user from selecting individual fi ...

Is there a way to stop the Firebase web client from altering the error message generated by an https.onRequest function?

I am facing an issue where I cannot retrieve the original message I sent from an "https.onRequest" function in Firebase. The firebase client is rewriting the message based on the error code, making it difficult for me to recover the originally sent body or ...

What is the process of developing a straightforward Node.js script to encapsulate a binary or executable file?

I am looking to develop a Node.js file that can seamlessly execute an executable binary file and handle all inputs and outputs, specifically targeting Windows operating systems. Reason for this: I aim to install an executable tool via npm install -g in or ...

JavaScript event listener for SVG path element click is not functioning correctly as anticipated

How to determine if an element or its children have been clicked? I am trying to identify when a parent element or any of its child SVG icons with the attribute name set to "setGameState" have been clicked. The issue I am facing is that sometimes the even ...

What is the best way to handle an OR scenario in Playwright?

The Playwright documentation explains that a comma-separated list of CSS selectors will match all elements that can be selected by one of the selectors in that list. However, when I try to implement this, it doesn't seem to work as expected. For exam ...

If a specific class is identified, add a border to the div when clicked using JavaScript

Is there a way to use javascript/jquery to add a border to a selected div? I have multiple rows with columns, and I want only one column per row to be highlighted with a border when clicked. Each row should have one column with a border, so it's clear ...

Utilize data retrieved from an API to customize the appearance of buttons through the combination of React and Sass styling techniques

I retrieved data from an API and used it to create a list of buttons. The data I received includes names and color codes. { name: "bob", colorCode: "#DC7472" }, { name: "ben", colorCode: "#69DCD1" }, { name: &q ...

Using JQuery to specify an attribute as "required" along with a value does not function as expected

Something seems off with this: $("#elementId").attr("required", "true"); In Chrome and Firefox, the DOM either displays required as the attribute (with no value) or required="" (empty value). Interestingly, it doesn't make a difference what value w ...

React Native reminder: Unable to update React state on a component that is unmounted

I am seeking clarity on how to resolve the issue in useEffect that is mentioned. Below is the data for "dataSource": [{"isSelect":false, "selectedClass":null, "zoneId":1026, "zoneName":"tomato"}, ...

What is the best way to ensure that the bootstrap nav tab content fits perfectly on one line?

Check out this bootstrap navbar example You can see a screenshot here. <ul class="nav nav-tabs" style="display: inlne-block"> <li class="nav-item" style="text-align: center; display: inline;"> <div> <a class="nav ...

"I have successfully removed the URL from index.html. However, I am now wondering how I can include them in app

I have modified the URL in index.html to remove query parameters, but now I need my app.component.ts file to still be able to access and work with those query params using ActivatedRoute. However, when I implemented the script in index.html to remove query ...

Plugin combination of Cordova File, InAppBrowser, and File Opener

I am experiencing an issue with opening a PDF file that I have stored using the File Plugin. I have tried using both the InAppBrowser and File Opener Plugin, but neither seem to work. I am currently using the Visual Studio Emulator KitKat for Android. Whe ...