How to extract a string using JavaScript Regex?
You need to use the m
flag:
multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string)
Also put the *
in the right place:
"DATE:20091201T220000\r\nSUMMARY:Dad's birthday".match(/^SUMMARY\:(.*)$/gm);
//------------------------------------------------------------------^ ^
//-----------------------------------------------------------------------|
function extractSummary(iCalContent) {
var rx = /\nSUMMARY:(.*)\n/g;
var arr = rx.exec(iCalContent);
return arr[1];
}
You need these changes:
Put the
*
inside the parenthesis as suggested above. Otherwise your matching group will contain only one character.Get rid of the
^
and$
. With the global option they match on start and end of the full string, rather than on start and end of lines. Match on explicit newlines instead.I suppose you want the matching group (what's inside the parenthesis) rather than the full array?
arr[0]
is the full match ("\nSUMMARY:..."
) and the next indexes contain the group matches.String.match(regexp) is supposed to return an array with the matches. In my browser it doesn't (Safari on Mac returns only the full match, not the groups), but Regexp.exec(string) works.
Your regular expression most likely wants to be
/\nSUMMARY:(.*)$/g
A helpful little trick I like to use is to default assign on match with an array.
var arr = iCalContent.match(/\nSUMMARY:(.*)$/g) || [""]; //could also use null for empty value
return arr[0];
This way you don't get annoying type errors when you go to use arr