Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 834
PapelPincel Avatar asked Nov 10 '09 11:11

PapelPincel


People also ask

How do you escape a string in regex?

The backslash in a regular expression precedes a literal character. You also escape certain letters that represent common character classes, such as \w for a word character or \s for a space.

What does .match do in JavaScript?

The match() method returns an array with the matches. The match() method returns null if no match is found.

What does \\ mean in regex?

\\. matches the literal character . . the first backslash is interpreted as an escape character by the Emacs string reader, which combined with the second backslash, inserts a literal backslash character into the string being read. the regular expression engine receives the string \.


1 Answers

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.

like image 141
j-g-faustus Avatar answered Sep 20 '22 14:09

j-g-faustus