Breaking down strings using delimiters in JavaScript

Looking for a solution to parse a string with markers:

'This is {startMarker} the string {endMarker} for {startMarker} example. {endMarker}'

I want to transform it into an array that looks like this:

[
    {marker: false, value: 'This is'},
    {marker: true,  value: 'the string'},
    {marker: false, value: 'for'},
    {marker: true, value:  'example.'}
]

Need some guidance on how I can achieve this while maintaining the sentence order and marker information. Any suggestions?

Answer №1

Here's a solution that might help

const my_str = 'This is {startMarker} the string {endMarker} for {startMarker} example.{endMarker}';

const my_arr = my_str.split('{endMarker}').reduce((acc, s) =>
                  s.split('{startMarker}').map((a,i) =>
                      a && acc.push({
                        marker: i ? true : false,
                        value: a.trim()}))
                      && acc,[]);
     
console.log(my_arr)

Answer №2

Just because you're a novice contributor...

interface HighlightedText {
   highlight: boolean
   textValue: string
}

function highlightTextContent(content: string): HighlightedText[] {
   let match: RegExpExecArray | null

   const firstMatch = content.slice(0, content.indexOf('{') - 1)
   
   const highlightedArray: HighlightedText[] = firstMatch.length > 0 ? [
      { highlight: false, textValue: firstMatch }
   ] : []
   
   while ((match = /\{(.+?)\}/g.exec(content)) !== null) {
      if (!match) break
   
      const highlightTag = match[0].slice(1, match[0].slice(1).indexOf('}') + 1)
   
      const markerEnd = match.index + match[0].length
   
      const value = content.slice(markerEnd, markerEnd + content.slice(markerEnd).indexOf('{')).trim()
   
      if (value === '') break
   
      if (highlightTag === 'startMarker') {
         highlightedArray.push({ highlight: true, textValue: value })
      } else if (highlightTag === 'endMarker') {
         highlightedArray.push({ highlight: false, textValue: value })
      }
   
      content = content.slice(markerEnd + value.length + 1)
   }
   
   return highlightedArray
}

Answer №3

const escapeRegex = s => s.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&");

        const extract = (start, end, str) => Array.from(
          str.matchAll(`(.+?)(${escapeRegex(start)}|${escapeRegex(end)}|$)`),
          ([, text, mark]) => ({
            marker: mark === end,
                value: text.trim()
          })
        );

        console.log(extract(
          "{startMarker}",
          "{endMarker}",
          "This is {startMarker} the string {endMarker} for {startMarker} example. {endMarker}"
        ));
        

Playground Link

Explanation

Regular Expressions

We have text segments that end with one of two markers. By using regular expressions, we can extract each section along with the corresponding marker.

This is {startMarker} the string {endMarker} 
  ^______^^___________^^__________^^_________^
  | text       mark   ||   text        mark  |
  ^___________________^^_____________________^
         section               section
  

The extracted text becomes the 'value' in the result object, while the marker segment can determine if it matches '{endMarker}' resulting in true or false.

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

What is the process of permanently modifying an HTML document using JavaScript?

I'm interested in creating a basic comment section using JavaScript. Here is the structure of the form : <form> <textarea cols="50" rows="10" placeholder="Share your thoughts ..." id="theComment"></textarea><br/> < ...

Bringing in External Components/Functions using Webpack Module Federation

Currently, we are experimenting with the react webpack module federation for a proof of concept project. However, we have encountered an error when utilizing tsx files instead of js files as shown in the examples provided by the module federation team. We ...

Creating dynamic ng-options in AngularJS

Below is an array: $scope.age = 2; $scope.people = [{name:"Sam",age:2},{name:"Pam",age:3},{name:"Ham",age:4}] The requirement is to make the ng-options dynamic. When age is 2, display all people objects in ng-options. If age is 1, show only the object wi ...

How can you arrange a List of Objects by property in Angular?

When working with Java, the Comparable interface can be utilized to sort Objects by specific fields. As shown in the example below, we are sorting Fruit objects based on their quantity. public class Fruit implements Comparable<Fruit> { private ...

What is the best way to instantiate objects, arrays, and object-arrays in an Angular service class?

How can I nest an object within another object and then include it in an array of objects inside an Angular service class? I need to enable two-way binding in my form, so I must pass a variable from the service class to the HTML template. trainer.service. ...

interactive textbox created with the combination of javascript and php

Hello, I am new to JavaScript and jQuery. I am trying to create a dynamic text box using JavaScript that can add and remove rows. When I press the add button, it works well, but when I pressed delete, it deleted the entire table. Below is my JavaScript fu ...

The Node function will yield a BluebirdJS Promise

I've encountered a minor issue with this script. While it functions properly, the "runTenant" method is not returning a promise that needs to be resolved with "all()". Here's the code snippet in question: Promise.resolve(runTenant(latest)).then ...

Getting into a dynamic named property inside another object in angular can be achieved by utilizing bracket notation

I encountered an issue in my Angular 8 project where I create an object from a JSON, but there is a dynamic property whose name is unknown until runtime. This causes problems when trying to access the value of that dynamic property within another object, l ...

Utilizing the onclick attribute in combination with a partial HTML button

When utilizing the onclick attribute in the HTML markup without using a partial tag, the onclick function is functional. However, when the exact same markup is used within a partial, the onclick function fails to execute. Query: Is there a method to make ...

What could be the reason for PassportJS in Node failing to clear the session upon logout?

I am encountering an issue with my system not successfully logging out using PassportJS. The logout route appears to be triggered, but the session is not being removed as intended. I would like it to return a 401 error if the user is not logged in on a spe ...

Navigate through each of the pictures within the folder and encode them into base64

I'm currently working on a project where I need to convert images in a folder to base64 and then store them in MongoDB. At first, I successfully converted a single image: var filename = '1500.jpg'; var binarydata = fs.readFileSync(filename ...

Creating JavaScript object fields with default values in an AngularJS model: A Step-by-Step Guide

As I work on developing the model layer for my AngularJS application, I came across some valuable advice on using functions to create objects. This source emphasizes the use of functions like: function User(firstName, lastName, role, organisation) { // ...

Issue with displaying Angular chart only resolves after resizing window following routing updates

Hey there! I'm having trouble getting my chart to show up after adding routing to my 3 tabs. Previously, without routing, everything worked fine. Now, the graph only appears after resizing the window. The chart is using PrimeNG chart with the Chart.js ...

Encountering an issue with an Uncaught SyntaxError: Unexpected identifier

I've been attempting to send data through ajax but keep encountering errors. Here's the code I have: jQuery.ajax({ url : '', type: 'POST', ...

Iterate over a collection of objects to find connections between the starting and ending points, and retrieve the number of occurrences

My challenge involves analyzing an array of objects containing origin and destination data, and the total volume of objects moving between locations. I am specifically looking to compare flow counts between two cities. For example, when the origin is Vanco ...

Unable to retrieve observable modifications

In my code file for handling reports, named report.service.ts, I have a method that retrieves reports data. This method simply returns a constant array of report objects from a mock source. Here is the implementation: @Injectable() export class ReportServ ...

Clearing the canvas completely with CamanJS: a step-by-step guide

I need some help with my CamanJS photo editing app. Everything is working perfectly except for one issue - when a user uploads a new image and applies a filter, the canvas reverts back to the previously uploaded image. Even though I am using the revert() f ...

Tips on automating the process of moving overflowing elements into a dropdown menu

Challenge Description In need of a dynamic navigation bar, I faced the problem of displaying only the first X items on one line and have the remaining items hidden in a "Show more" dropdown. The challenge was to calculate the width of each item accurately ...

Enhance your AngularJS skills by incorporating multiple conditions into the ternary operations of ng-class

I am struggling to apply multiple classes when the condition in the ng-class attribute evaluates to true. Here is the code I have attempted so far, but it doesn't seem to be working: <div class="col-md-4" ng-mouseover="hoverButton=true" id="plai ...

What is the best way to display the value of a new object's property in Angular?

I am currently developing a list application that allows users to create new lists by entering a name and clicking a button. Once the list is created, users can add and remove items from the list. However, I have encountered an issue where the name of the ...