1

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.

Patrick Hund
  • 17,059
  • 10
  • 61
  • 91

2 Answers2

1

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);
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
-1

Here you go (step by step):

const str = `
+++DELIMITER 1+++

text

+++DELIMITER R+++

text 2

+++NAME OF DELIMITER+++

text n
`
// first replace the +++ with ''
const strr = str.replace(/\+{3}/g, '')

// place them in an array
const strArr = strr.split('\n').filter(r=>r!=='')

//push each next two values in separate array
const finalArr = []
while(strArr.length) finalArr.push(strArr.splice(0,2))

console.log(finalArr)
Bhojendra Rauniyar
  • 78,842
  • 31
  • 152
  • 211