adam78
adam78

Reputation: 10068

jQuery Regular expressions to extract string?

I have the following string with line breaks \r\n:

var myString = "DTSTART:20161009T160000Z
                DTEND:20161009T170000Z
                RRULE:FREQ=DAILY;UNTIL=20161015T000000Z;INTERVAL=1;BYDAY=SU,MO,TU,WE,TH,FR,SA
                EXDATE:20161009T160000Z"

I want to extract the rrule as follows:

FREQ=DAILY;UNTIL=20161015T000000Z;INTERVAL=1;BYDAY=SU,MO,TU,WE,TH,FR,SA

Currently I can achieve this by doing the following

var subStr = myString.match("RRULE:(.*)\r\n");
alert(subStr[1]);

Sometimes the EXDATE line doesn't exist in which case there is no \r\n after the RRULE line. Anyone know of a cleaner way to do it without having to output using an array index?

Upvotes: 1

Views: 6084

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626826

You do not need the \r\n at all since . matches any symbol but a linebreak symbol (neither \r, nor \n). A mere /RRULE:(.*)/ can work for you. For better precision, you may specify you want a RRULE that is at the start of a line with

/^\s*RRULE:(.*)/m

See the demo:

const myString = `DTSTART:20161009T160000Z
                DTEND:20161009T170000Z
                RRULE:FREQ=DAILY;UNTIL=20161015T000000Z;INTERVAL=1;BYDAY=SU,MO,TU,WE,TH,FR,SA`;
let m;
m = myString.match(/^\s*RRULE:(.*)/m);
if (m) {
 console.log(m[1]);
}

Upvotes: 3

Related Questions