skip to Main Content

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.

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. You can do it one line like this.

    let arr = [
        "First sentence ",
        "Second sentence",
        "Third sentence {variable}",
        "Fourth sentence {variable} with other data {variable2}",
        "Fiftth sentence {variable} with additional data {variable2}",
        "Sixth sentence"
    ]
    console.log(arr.toString().replaceAll('} ','},').split(','))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search