Dividing the text by its position value and adding it to a fresh object

I needed to divide the paragraph into sections based on its entityRanges.

Here is what the original paragraph looks like:

{
    type: 'paragraph',
    depth: 1,
    text: 'Do you have questions or comments and do you wish to contact ABC? Please visit our customer support page.',
    entityRanges: [{
        type: 'LINK',
        offset: 83,
        length: 16,
        data: {
            target: '_self',
            url: '/index.htm'
        }
    }]
}

However, I was expecting the following results:

{
    type: 'paragraph',
    depth: 1,
    text: 'Do you have questions or comments and do you wish to contact ABC? Please visit our customer support page.',
    entityRanges: [{
        type: 'LINK',
        offset: 83,
        length: 16,
        data: {
            target: '_self',
            url: '/index.htm'
        }
    }],
    embbeded: [{
        type: 'text',
        text: 'Do you have questions or comments and do you wish to contact ABC? Please visit our '
    }, {
        type: 'link',
        text: 'customer support',
        data: {
            target: '_self',
            url: '/index.htm'
        }
    }, {
        type: 'text',
        text: 'page.'
    }]
}

I aimed to break down the text into multiple segments based on its offset & length values.

For instance, in the given example, customer support is the offset value.

Thus, it should be divided in the following sequence:

  1. Do you have questions or comments and do you wish to contact ABC? Please visit our
  2. customer support
  3. page.

All of the above segments need to be moved to a new object called embbeded.

Answer №1

Hopefully, I have interpreted your message correctly:

const info = {
  "text": "If you have any questions or feedback and would like to get in touch with XYZ, please check out our customer support page.",
  "entityRanges": [{
      "type": "LINK",
      "offset": 83,
      "length": 16,
      "data": {
        "target": "_self",
        "url": "/index.htm"
      }
    },
    {
      "type": "LINK",
      "offset": 7,
      "length": 4,
      "data": {
        "target": "_self",
        "url": "/index.htm"
      }
    }
  ]
};

function splitData(info) {
  let {
    entityRanges,
    text
  } = info;
  const output = [];
  let lastPart = '';
  let idx = 0;

  entityRanges
    .sort((a, b) => a.offset - b.offset)
    .forEach((styleRange) => {
      const {
        offset,
        length,
        type,
        data
      } = styleRange;
      const firstSeg = text.substring(idx, offset);

      output.push({
        type: 'text',
        text: firstSeg,
      });

      idx = offset + length; // + 1;
      const secondSeg = text.substring(offset, idx);
      output.push({
        type,
        data,
        text: secondSeg,
      });

      lastPart = text.substring(idx);
    });

  if (lastPart) {
    output.push({
      type: 'text',
      text: lastPart,
    });
  }
  info.embbeded = output;

  return info;
}

const result = splitData(info);

document.body.innerHTML = '<pre>' + JSON.stringify(result, null, ' ') + '</pre>';

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

Revolutionize Your App with React Native's Interactive Bottom Sheet Option

Hello there! I am trying to create a FlatList with multiple items, each of which should trigger a bottom-sheet when clicked. I want to make this dynamic but I'm encountering an error. TypeError: undefined is not an object (evaluating `_this[_reactNat ...

Cause a malfunction in the triggering function of jQuery

$(document).ready(function(){ jQuery("#but1").bind("click",function(e){ alert(e.name); }); jQuery("#but1").trigger({name:'Dmy', surname:'My'}); }); The information doesn't seem to be getting passed correctly a ...

How can I use JavaScript regex to extract the first term to the left of a specific symbol?

Having a string in this format str = "Is toffee=sweet?" I need to retrieve the first term on the left side of =, which in this case is toffee. To accomplish this, I use the following code snippet: str.split("=")[0].split(" ").splice(-1,1)[0] This retu ...

What is the best way to transfer information from a view to a controller in Laravel using AJAX?

I am facing an issue with sending data from the view to the controller in Laravel version 7 I am sending data from a form and ul li elements I have an array of data in JavaScript Here is my HTML code: <ul name="ali" id="singleFieldTags&q ...

When using Jest, it is not possible to match 'undefined' using 'expect.any(Object)' or 'expect.anything()'

Looking to test the following module. import * as apiUtils from './apiUtils'; export function awardPoints(pointsAwarding) { return apiUtils.callApiService("POST", "points", pointsAwarding); } This is the test in question. it("should call ap ...

Getting latitude and longitude from Google Maps in a React Native appHere are the steps to

Looking to retrieve the latitude and longitude from Google using React Native. As a newcomer to React Native, I have been unable to find any resources to address this issue. Any assistance would be greatly appreciated. Thanks! Thanks ...

Using a prop array as v-model in a Vue JS CheckBoxGroup implementation

Struggling to create a reusable CheckBoxGroup component with a prop array as v-model. I checked out the vuejs guide at https://v2.vuejs.org/v2/guide/forms.html#Checkbox which uses the v-model array in the data of the same component. However, this approach ...

Establish a many-to-many relationship in Prisma where one of the fields is sourced from a separate table

I'm currently working with a Prisma schema that includes products, orders, and a many-to-many relationship between them. My goal is to store the product price in the relation table so that I can capture the price of the product at the time of sale, re ...

The ReactJS Application Cache Client fails to display the most recent updates

One issue I'm currently facing is with my application in production. Some clients have reported that they are unable to see the new changes unless they clear their cache completely. Using Techs: React Any suggestions on what steps I should take to a ...

The Mystery of the Undefined Return Value in JavaScript's Map Function

My array contains around 1000 elements. I'm encountering a situation where the map function returns undefined for certain indexes. Is there a method to only retrieve values that meet a specific condition? I want to filter out elements with values less ...

What causes the issue of text being blocked by a webgl shader background even when the text div is layered above and given a higher z-index?

I am looking to enhance a WordPress theme by dynamically generating glsl shaders using the three.js library for JavaScript, and then incorporating those shaders into various HTML elements, such as using them as backgrounds for text content. My current cha ...

Exploring the capabilities of AngularJS2's formGroup and formControlName functionality

Exploring the world of AngularJS2, I recently created a sign-up page utilizing formGroup formControlName, but encountered an issue with passing null values to the object. HTML code: <div class="col-md-8 col-md-offset-2"> <form [formGroup]="m ...

parsing a TypeScript query

Is there a simpler way to convert a query string into an object while preserving the respective data types? Let me provide some context: I utilize a table from an external service that generates filters as I add them. The challenge arises when I need to en ...

Guard does not prompt router redirection

My angular app running Angular 15 is facing an issue with the App-routing module not redirecting when a guard returns the UrlTree. app-routing.module.ts import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular ...

Restricting JSON output using date and time values within the JSON object

Currently, I'm in the process of creating a play data reporting tool specifically designed for a radio station. The main concept involves retrieving play history from the playout software's API and manually adding tracks that were played outside ...

Is it possible to extract data from a JavaScript Array using scraping techniques?

I have a sample page that I want to extract data from... [ [4056, 1, 'Saturday, Aug 18 2012', '15:00', 171], [4057, 1, 'Saturday, Aug 18 2012', '15:00', 94], [4058, 1, 'Saturday, Aug 18 2012', '15:00& ...

Importing local JSON files into Vuex state

I am looking to import data from a local JSON file into a state value setting within my Vue.js application. store/index.js import { createStore} from 'vuex' export default createStore({ state: { settings: {} } }) assets/json/settings.j ...

Automatically Refresh a Div Element Every 5 Seconds Using jQuery's setInterval() Function

My goal is to refresh the left div every 5 seconds using $.ajax to get JSON data and display 4 random elements in that div. However, even though the left div block refreshes, the content remains the same with the same images always showing. view image desc ...

Tips on redirecting a user to a specific page after they have made a selection without doing so immediately

I am a beginner in the world of coding. Currently, I am working on creating templates for an online software application. Users will have the option to select from different choices using radio buttons. However, I want to ensure that users are not redirect ...

Learn how to trigger a re-render in React to update a value stored in local storage

I need assistance in displaying a spinner with a percentage value during file uploads within my React application. To achieve this, I am utilizing Material UI's circular progress. My approach involves making a REST call using Axios to obtain the perce ...