简体   繁体   中英

How to split data in a Google Slides Table (based on character limit) in multiple rows coming in from a Google Sheet using Google Apps Script?

I've written a Google Apps Script that reads data from a Google Sheet and for each row, it creates a new slide using a template I've created in the first Slide:

Template Slide:
模板幻灯片

My template Google Slide has a Table, which populates with data from one of the columns in the Google Sheets. I've been able to get the data populated as expected on the sheet, but when the data in one of the table cells exceeds a certain limit, it flows out of the slide:

Overflowing Text in a Cell:
单元格中的溢出文本

I am attempting to make a duplicate of the overflowing slide and continuing the overflown text in the next slide. The other columns and cells stay the same.

To do this, I have the following idea in mind:

//For each row in the input google sheet, do:
//    For each column, get indices of "." (period) in an array.
//        For each "." closest to a multiple of SPILLOVER_CHARACTER_LIMIT (a constant, like 500)
//            Split the array into a sub-array.
//        [#] Split text in the overflowing cell at the last array element of each sub-array.
//        [#] Store the splits in a master array at the index of the current column.

//    Now, in the 2D Master Array:
//        [#] reconstruct rows
//        Example:[["Col1_Part1","Col1_Part2","Col1_Part3"],["Col2_Part1",,],["Col3_Part1","Col3_Part2",]] ---becomes---> [["Col1_Part1","Col2_Part1","Col3_Part1"],["Col1_Part2",,"Col3_Part2"],["Col1_Part3",,]]
//
//    Continue to make each row into a slide as before. Overflow is handled.

As described, this splitting is occurs at sentence terminations. If I set my limit to be a multiple of 500 characters, I'm trying to get the index of the closest period, say 497 or 502, 1501 or 1499, and so on. That's the point where I want to split the input string, to identify where the next slide should continue (This is actually to make a sensible split, and not a hard 500 character split which could potentially cut a word or a sentence in parts).

In the pseudocode shared above, the steps I've marked with [#] are something I am not quite able to wrap my head around. I could do it in a few ways, but they involve quite a lot of code. The entire approach I think is inefficient and could result in having to nest loops. I am looking for a better way to split the input row into multiple slide table rows, if there is one.

Please feel free to suggest an entirely different approach, this is just one of the ways I'm trying to split the row. (Also please let me know if I can frame my question better! I'm new.)

To split by the first period after 500 characters:

Please be reminded the last part would be missing that you have to handle it

value.match(/.{500,}?\./g)

An example with split every 5 characters:

 const value = '12345.1234.123.123456.12345.12.' console.log(value); const matches = value.match(/.{5,}?(\\.|$)/g); console.log(matches); const result = [...matches, value.replace(matches.join(''), '')]; console.log(result);

Answer:

In order to get the character nearest to the 500 mark, you can loop through the indices of all . characters and use the modulo operator to get it's positional variance from a multiple of 500.

Code & Explanation:

Code Breakdown:

  • Using /\\./g as a regular expression, you can obtain all indices of . characters and push them to the matchIndices array.
  • You can then map these indices using the modulo operator:
    • Math.abs(characterIndex - (x % characterIndex)) will return the value for how far away from a multiple of your character index you are. For example, if the index is 489, then this mapping will return 11.
  • After obtaining all the index variances, you can loop through these moduli and return only the trough values - that is to say, all values where the previous and next entries are higher values.
  • Add a -1 value to the beginning of this array in order to start at the beginning of the text when looped through.
  • Go through each of these break points, and split the original text around the, adjusting by +1 to capture the . character as well.
  • Finally, trim the whitespace on each of the array values and join then with a newline \\n .

Example in action:

 const text = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras porttitor ut sem id vulputate. Suspendisse massa urna, placerat sed molestie non, consectetur a ligula. Donec venenatis tincidunt nisi, quis blandit tellus luctus vel. Praesent vitae tortor sem. Fusce libero orci, auctor volutpat ullamcorper sit amet, condimentum a sem. Mauris mollis ultricies risus, ac porttitor ipsum consequat quis. Cras in nisl sed neque finibus pellentesque. Ut pellentesque congue odio quis viverra. Donec tellus mauris, egestas quis arcu non, dapibus laoreet augue. Morbi et viverra augue. Etiam hendrerit sodales nibh eget egestas. Morbi ac eleifend lacus. Phasellus tempor facilisis convallis. Ut ultricies velit justo, ut consectetur est aliquam non. Quisque molestie aliquet sagittis. Vivamus varius, enim id bibendum lobortis, ante urna mattis libero, sit amet efficitur libero est vulputate tellus. Aliquam magna quam, laoreet nec lacinia sed, faucibus eu odio. Etiam id tortor rutrum, luctus neque pellentesque, tincidunt metus. Nulla facilisi. Cras facilisis, massa eget tempus rhoncus, turpis massa convallis ex, non congue ipsum metus id risus. Vestibulum id justo in purus vulputate egestas. Donec a semper diam, eget sodales nibh. Donec eu sagittis tortor, eu iaculis nunc. Phasellus posuere iaculis erat, nec semper tellus faucibus id. Donec tempus sapien ac augue malesuada rhoncus. Phasellus at condimentum velit, at pellentesque mi. Nullam at urna elementum, sodales nibh sed, finibus risus. Quisque velit erat, tempus vehicula erat eget, laoreet viverra purus. Praesent viverra neque et quam porttitor efficitur. Nulla facilisi. Integer fermentum nulla eget magna sagittis dignissim. Vestibulum dignissim ullamcorper elit, sit amet semper leo pulvinar sit amet. In urna dui, faucibus vitae nulla a, tincidunt commodo libero. Pellentesque lacus quam, blandit sit amet sapien vel, iaculis semper velit. Donec justo urna, sollicitudin eget justo eget, finibus viverra elit. Phasellus mollis sodales felis a cursus. Nullam odio turpis, convallis sit amet augue sit amet, sodales mattis nulla. Nulla eget tristique ex. Morbi vitae elit neque. Etiam nec sem dapibus, congue velit vel, lacinia nibh. Vestibulum congue convallis rutrum. Etiam nec lacus nulla. Nulla feugiat non urna eu efficitur. Nullam laoreet mollis dolor, sed iaculis tortor. Aenean vitae augue ante. Donec nisl ligula, ullamcorper sed lacus at, pulvinar placerat justo. Nullam facilisis risus nec lorem lobortis semper. Suspendisse in mi dolor. Fusce maximus eros id ex vehicula tincidunt. Sed eget hendrerit mauris. Vestibulum venenatis dictum nibh, ac blandit orci pellentesque et. Ut facilisis fermentum justo, et condimentum metus convallis ac. Nulla enim risus, scelerisque in scelerisque et, ullamcorper a est. Sed vehicula sed nibh vitae pulvinar. Curabitur tempor id augue non tristique. Aliquam tempus dui metus, et imperdiet arcu rutrum eget. Mauris cursus arcu sem, eu gravida est interdum eget. Mauris sed nunc consequat, bibendum sapien eget, dapibus quam. Etiam sodales nibh non pellentesque fermentum. Proin ut dapibus augue, vitae faucibus ante. Donec viverra ante quam. Fusce ac ornare nisi, eget pulvinar eros.` function breakUpText(text, characterIndex) { const regEx = /\\./g const matchIndices = [] let curr while ((curr = regEx.exec(text)) !== null) { matchIndices.push(curr.index); } const moduli = matchIndices.map(x => (Math.abs(characterIndex - (x % characterIndex)))) let breaks = [] for (let i = 0; i < moduli.length; i++) { if (moduli[i + 1] > moduli[i] && i !== moduli.length) { breaks.push(matchIndices[i]) } } breaks.unshift(-1) const parts = [] for (let i = 0; i < breaks.length; i++) { parts.push(text.substring(breaks[i] + 1, breaks[i + 1] + 1 || text.length)) } return parts.map(x => x.trim()).join("\\n") } console.log(breakUpText(text, 500))

You can call the break-up text function by passing the text you want to split, and the index around you wish to split the text.

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM