How to extract a string using JavaScript Regex?

Viewed 329893

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);
}
7 Answers

This code works:

let str = "governance[string_i_want]"; 
let res = str.match(/[^governance\[](.*)[^\]]/g);
console.log(res);

res will equal "string_i_want". However, in this example res is still an array, so do not treat res like a string.

By grouping the characters I do not want, using [^string], and matching on what is between the brackets, the code extracts the string I want!

You can try it out here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_match_regexp

Good luck.

You should use this :

var arr = iCalContent.match(/^SUMMARY\:(.)*$/g);
return(arr[0]);
Related