javascriptregexstringicalendar

How to extract a string using JavaScript Regex?


I'm trying to extract a substring from a file with JavaScript Regex. Here is a slice from the file :

DATE:20091201T220000
SUMMARY:Dad's birthday

the field I want to extract is "Summary". Here is the approach:

extractSummary : function(iCalContent) {
  /*
  input : iCal file content
  return : Event summary
  */
  var arr = iCalContent.match(/^SUMMARY\:(.)*$/g);
  return(arr);
}

Solution

  • You need to use the m flag for ^ and $ to work as expected:

    [...] if m is used, ^ and $ change from matching at only the start or end of the entire string to the start or end of any line within the string.

    Also put the * in the right place:

    let iCalContent = "DATE:20091201T220000\r\nSUMMARY:Dad's birthday";
    let result = /^SUMMARY\:(.*)$/gm.exec(iCalContent);
    console.log(result && result[1]);