Carondimonio
Carondimonio

Reputation: 71

JavaScript Regular Expression String Split

What I have is a string that I want to split.

I can set delimiters inside the string for example:

+++DELIMITER 1+++

text

+++DELIMITER R+++

text 2

+++NAME OF DELIMITER+++

text n

...

Edits after questions:

The string does not contain linefeed characters, An example of string wourld be:

let string = "+++DELIMITER 1+++ text +++DELIMITER R+++ text 2 +++NAME OF DELIMITER+++ specialchars \"£$%%£$\"<>";

text n";

What i want to obtain is an array constructed like this:

resultarray=[
     ["DELIMITER 1", "text"],
     ["DELIMITER R", "text 2"],
     ["NAME OF DELIMITER", "text n"]
     ...
];

I think I have to use String.split method, but I don't know what kind o f regex to use.

Upvotes: 1

Views: 134

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386550

You could split the string and reduce single strings to pairs.

var string = '+++DELIMITER 1+++text+++DELIMITER R+++text 2+++NAME OF DELIMITER+++text n',
    parts = string
        .split(/\+{3}/)
        .slice(1)
        .reduce((r, s, i) => r.concat([i % 2 ? r.pop().concat(s) : [s]]), []);
    
console.log(parts);

Upvotes: 1

Related Questions