Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

split text items in an array

I have an array like the following

[
  "First sentence ",
  "Second sentence",
  "Third sentence {variable}",
  "Fourth sentence {variable} with other data {variable2}",
  "Fiftth sentence {variable} with additional data {variable2}",
  "Sixth sentence"
]

I want to split the items in the array with the following conditions

if there is a variable (curly bracket) and there is content after the variable, that line should be split into 2 lines. If there is no content after the variable it can be kept as it is.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For example following is the output i need

[
 "First sentence ",
 "Second sentence",
 "Third sentence {variable}",
 "Fourth sentence {variable}",
 "with other data {variable2}",
 "Fiftth sentence {variable}",
 "with additional data {variable2}",
 "Sixth sentence"
]

What i tried so far is as follows

convertLogicsArray(sentenceArray: string[]): string[] {
    const newSentenceArray: string[] = []
    for (const sentence of sentenceArray) {
      // Split the sentence into two parts at the variable.
      const parts = sentence.split('{', 1)
      // If there is text after the variable, make the sentence two lines.
      if (parts.length === 2) {
        newSentenceArray.push(parts[0])
        newSentenceArray.push(parts[1])
      }
      // Otherwise, leave the sentence as one line.
      else {
        newSentenceArray.push(logic)
      }
    }
    return newSentenceArray
  }

It does not return the exact response i need.

How can i form the array as shown in the question when provided with the original array

>Solution :

Flat-map the array, splitting each entry on a lookbehind regex matching your variable format

const sentenceArray = [
  "First sentence ",
  "Second sentence",
  "Third sentence {variable}",
  "Fourth sentence {variable} with other data {variable2}",
  "Fiftth sentence {variable} with additional data {variable2}",
  "Sixth sentence"
];

const newSentenceArray = sentenceArray.flatMap((str) =>
  str.split(/(?<=\{\w+\})/).map((s) => s.trim()),
);

console.log(newSentenceArray);

I’ve also used String.prototype.trim() to remove the spaces after variables.

Note: Lookbehind doesn’t work in IE or Opera Mini if that matters

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading