Find variable substring after known characters inside a string

137 views Asked by At

I have the following RRULE in a string format:

DTSTART;TZID=America/Toronto:20160909T040000RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=MO,WE,FR;UNTIL=20161202T040000

I want to parse the properties of the string into their own respective variables to use inside form inputs to update. The same RRULE properties are going to show up in every string so I know for example that DTSTART will always be in the string.

I thought about using the string method search by specifying the property by its name and then adding the number of characters to add to get the position of the entity and want and then use .substring()

So for example, if I was trying to extract UNTIL, I could do:

export const parseUntilFromRRule = (rrule: string):Date => {
    const posInRRule = rrule.search("UNTIL=");
    const until = rrule.substring(posInRRule + 6);

    return new Date(until);
};

However, for properties in the middle of the string, where the value's length may vary, this method would not work because I would not know the value of the second parameter to pass into substring

What generalized technique can I use to extract each RRULE property from the string?

2

There are 2 answers

0
Tim Biegeleisen On BEST ANSWER

I would use string split twice here:

var input = "DTSTART;TZID=America/Toronto:20160909T040000RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=MO,WE,FR;UNTIL=20161202T040000";
var rrule = input.split("RRULE:")[1].split(";")[0];
console.log(rrule);

1
CertainPerformance On

You can split by semicolons, then split each result by = if an entry contains a =, and turn the result into an object:

const input = `DTSTART;TZID=America/Toronto:20160909T040000RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=MO,WE,FR;UNTIL=20161202T040000`;

const segments = input.split(';');
const entryKeyValues = Object.fromEntries(
  segments.map(
    segment => segment.includes('=')
      ? segment.split('=')
      : [segment, '']
  )
);
console.log(entryKeyValues);
console.log(entryKeyValues.UNTIL);