-2

Is there a function in Java Script that divide a string with several arguments?

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

For example, I can split with , by saying string.split(','); and I will have:

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

Now, I want to split it with several parameters, so string now would be

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

I'm looking for a function that extract all the parts that start with test and end with text.

8
  • 6
    Use regular expressions.
    – Aᴍɪʀ
    Sep 8, 2016 at 16:24
  • Are you sure you don't want to just replace some text before splitting?
    – Mike Cluck
    Sep 8, 2016 at 16:25
  • 1
    please clarify your question - it's not clear what you really want to achieve.
    – Lyubomir
    Sep 8, 2016 at 16:27
  • /test(.+)text/g?
    – Mike Cluck
    Sep 8, 2016 at 16:32
  • 2
    If people are asking you to clarify, then it, obviously, was not clear to them. Saying "think that everything is clarified enough" comes off as arrogant. Something more along the lines of "I'm sorry what I posted did not communicate clearly. I'm not sure how I could clarify it for you. What does not appear to be clear?" would probably result in better communication.
    – Makyen
    Sep 8, 2016 at 16:34

2 Answers 2

0

I'm not sure that I understood what you want, but here is a function I wrote in 2 minutes. With the following 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"));

it will output ["test text", "testing text"].

Let me know if it helps you.

EDIT

Corrected a wrong behave with a particular string. Please remind that I wrote it in a couple of minutes.

2
  • This helped. Thanks a lot! Sep 8, 2016 at 17:22
  • You're welcome! Please check the updated answer, as the function had a wrong behaviour with a particular string, and please bear in mind that it's just a quick example. Adapt it to your needs.
    – Alessandro
    Sep 8, 2016 at 17:27
0

Use a regex:

var str = "This is a test text, again, this is a testing text";
console.log(str.match(/test.+?text/g));

Not the answer you're looking for? Browse other questions tagged or ask your own question.