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
Flat-map the array, splitting each entry on a lookbehind regex matching your variable format
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
You can do it one line like this.