1

This code's goal is to take a multi-line string input (from a single cell in Google Sheets) and break it into pieces to the point where math operations can be performed for a total run mileage figure as the end result.

Example multi-line string input:

"2.5mi warmup
100met sprint
200met slow
repeat 4x
2mi tempo
1mi slow
repeat 8x
1mi jog
200met walk
repeat 4x
5mi cooldown"

After filtering out the first and last lines and then performing a split function using /x/ as the regex, I have the following array:

//arraysplitrepeatblocks = 
[ '  \n100met sprint \n200met slow \nrepeat 4',
  ' \n2mi tempo \n1mi slow \nrepeat 8',
  ' \n1mi jog \n200met walk \nrepeat 4',
  ' \n ' ]

I am trying to clean up this data by removing any mentions of "\n" from each string within the array. I tried the code below but it is not an accepted function (I'm assuming due to the object being an array instead of a string; perhaps some iteration is necessary).

let arraycleanedup = arraysplitrepeatblocks.replace(/\s+\\n/,"");

//Error given:
TypeError: arraysplitrepeatblocks.replace is not a function

Expected result:

[ ' 100met sprint 200met slow repeat 4',
  ' 2mi tempo 1mi slow repeat 8',
  ' 1mi jog 200met walk repeat 4',
  ' ' ]

Any advice would be appreciated. Also, is there a way to delete that final empty array element? If so, the expected result after that operation would be:

[ ' 100met sprint 200met slow repeat 4',
  ' 2mi tempo 1mi slow repeat 8',
  ' 1mi jog 200met walk repeat 4']
8
  • 1
    what language is this? Commented Feb 9, 2024 at 19:48
  • My fault. I am working in Javascript. Updated title. Commented Feb 9, 2024 at 19:51
  • replace is indeed not a function on arrays. Did you mean to loop over the array and call replace on each string? Commented Feb 9, 2024 at 19:52
  • Use Array.prototype.map() to perform the same replacement on each element of the array. Commented Feb 9, 2024 at 19:54
  • 2
    Does this answer your question? Replace string in javascript array Commented Feb 9, 2024 at 19:59

1 Answer 1

0
const result = [
  '  \n100m sprint \n200m slow \nrepeat 4',
  ' \n2mi tempo \n1mi slow \nrepeat 8',
  ' \n1mi jog \n200m walk \nrepeat 4',
  ' \n '
].reduce((acc, string) => {
  const formattedStr = string.replace(/^\s+|\s+$/g, ''); // Remove leading and trailing whitespaces
  if (formattedStr !== '') {
    acc.push(formattedStr);
  }
  return acc; // Return the accumulator in each iteration
}, []);

console.log(result);
Sign up to request clarification or add additional context in comments.

1 Comment

Try testing if /^\s+|\s+$|\n/g matches the new line within formattedStr to be removed?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.