separate elements in an array into individual text items

My array consists of sentences like the ones below:

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

I aim to split the items in the array based on specific conditions.

If a line contains a variable within curly brackets and has content following it, that line should be divided into two lines. Otherwise, it can remain as is.

The desired output is demonstrated below:

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

In my attempt at solving this, I have created the following method:

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
}

However, this approach does not achieve the exact outcome I desire.

How can I manipulate the array to match the structure outlined in the question when given the original array?

Answer №1

Utilize flat-map on the array, breaking down each entry using a lookbehind regex pattern that matches your unique 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 implemented String.prototype.trim() to eliminate spaces following the variables.

Important: Please note that Lookbehind functionality is not supported in IE or Opera Mini

Answer №2

Completing this task is simple with just one line of code.

let list = [
    "First step ",
    "Second step",
    "Third step {variable}",
    "Fourth step {variable} along with other information {variable2}",
    "Fifth step {variable} including extra details {variable2}",
    "Sixth step"
]
console.log(list.toString().replaceAll('} ','},').split(','))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Distinguishing between TypeScript versions 2.0.x and 2.1.x using type definitions and filtering with a switch/case statement

@ngrx/store (an observable redux implementation for angular (2) ) utilizes a specific pattern to assign the correct type to a reducer. Check out the actual code here. export const ActionTypes = { FOO: type('foo'), BAR: type('bar&apos ...

Adding a static javascript file to a Vue CLI 3 project is a straightforward process

Currently working on a vue-cli-3 project and looking to include a static javascript file. Curious about the proper way to import this file. The typical method used is: <script src="js/myfile.js"></scrip> ...

Troubles encountered while implementing crypto-js in Parse Cloud Code for an iOS mobile app

For my iOS app, I have implemented Parse as the backend and want to ensure the data transmitted between Parse and the device is encrypted. To achieve this, I have turned to Parse Cloud Code for server-side encryption and decryption of all data exchanges. ...

Server error occurs in NodeJS site when the MongoDB database is not empty

I am currently utilizing Node.js in conjunction with MongoDB and Mongoose to facilitate my database connectivity. An intriguing issue arises when the database lacks any values: the callback function successfully renders the subsequent page (albeit without ...

jQuery: Repeated Triggering of Button Click Event

At my website, I am facing an issue with multiple buttons being loaded twice via ajax from the same file. The problem arises when the event associated with a button fires twice if that same button is loaded twice. However, it functions correctly if only o ...

Using JavaScript to replace strings with values from an array in a Node Array

I have used custom JavaScript in GTM to create an array that needs some manipulation before generating a final value. Here are the initial values in my array: Array = [ [AED1,299.00], [AED2,699.00] ] My goal is to remove "AED" and commas from the values ...

Importing custom pipes in Angular 2 becomes a bit tricky when working with data grouping

As a newcomer to Angular JS, I have recently started using Angular 2 for a project of mine. Here is an example of my JSON data: "locations": [ { "id": "ASS", "name": "test center", "city": "Staten Island", "zip": ...

Is there a reason for TypeScript compiler's inability to effectively manage filtering of nested objects?

Perhaps a typical TypeScript question. Let's take a look at this simple filtering code: interface Person { id: number; name?: string; } const people: Person[] = [ { id: 1, name: 'Alice' }, { id: 2 }, { id: 3, name: 'Bob&apos ...

What is the best way to reset the timeout in JavaScript/jQuery?

I have a situation on my webpage where modifying field A triggers an API call through jQuery to update field B. Subsequently, the API should be called every 10 seconds to keep field B updated. Currently, this is achieved using: setTimeout(thisFunction, 10 ...

Tips for showcasing the latter portion of text within an HTML select dropdown menu

I have a select drop-down list with a fixed width of 80px, as shown in the image below: https://i.sstatic.net/pCpI9.png <select id="dd_country_code_2" name="dd_country_code_2" style="width: 120px; height: 23px;"> <option value="SEL">(Cou ...

Ways to avoid data looping in jQuery Ajax requests

This is in relation to the assignment of multiple users using the Select2 plugin, Ajax, and API. The situation involves a function that contains 2 Ajax calls with different URLs. Currently, there are pre-selected users stored in the database. The selection ...

How can I limit props.children in a React TypeScript component?

import React from 'react'; import './App.css'; import Message from "./components/Message"; function App() { return ( <div className="App"> <Message> <p>Hello ...

Using auto-fit or auto-fill with CSS grid-template-columns can cause unexpected behavior and may not work as

I am currently working with this particular component: <template> <div id="cms-img-upload-multiple" class="cms-img-upload-multiple"> <input class="btn-upload" v-if="!state.images.length" type=&qu ...

What is the best way to incorporate images from an external module into my React project?

Is there a way to include images from an external module (npm install external-module) in my project's public assets? The images are located in the directory path myProject/node_modules/external-module/dist/img. ...

Having trouble with vscode [ctrl+click] on 'vue single-file components' and 'go to definition'? It's not working for me

// src/ui/tabbar/Index.vue <template> <div> my-tabbar component here </div> </template> // src/ui/index.js import MyTabbar from './tabbar/Index.vue' export default { install(Vue) { Vue.component(MyTabbar.na ...

Derive a generic intersection type by extracting various types from an array within a function argument

I am in the process of extracting a common type that combines the types of objects found within an array passed as an argument to a function. To better explain this concept, consider the following code: type Extension = { name: string, fields: { [k ...

There is no matching overload for this call in React Native

I am working on organizing the styles for elements in order to enhance readability. Here is the code I have written: let styles={ search:{ container:{ position:"absolute", top:0, }, } } After defining the s ...

Issue with AngularJs failing to display data

As a newcomer to AngularJS, I am looking to utilize AngularJs to display the Json output from my MVC controller. Here is the code snippet for my MVC Controller that generates Json: [HttpGet] public JsonResult GetAllData() { ...

Updating the view in AngularJS with a service to keep users engaged even when they are offline

I'm currently developing an application that requires the ability to detect when a user loses internet connection or is unable to reach the server. Various controllers and services should be able to check and update this status easily. I have successf ...

Troubleshooting: JQuery Ajax Post triggering 500 Internal Server Error

I've encountered an issue while trying to execute this AJAX post. Despite hitting break points in the controller, I keep receiving a server 500 error. It seems like the problem lies within the callback function. Any ideas on how to resolve this? $.aj ...