1

I recently came across a great SO thread that uses Google App Scripts to save multipart uploads from a form to a Google Drive. One line in that answer calls:

.replace(/^.*,/, '')

on a base64 encoded representation of a file upload. My question is: what does this regular expression do?

Using a regex parser, it seems that this should start at the beginning of a string, match any character any number of times, but that would replace the entire string with '', so I'm clearly not grokking this simple operation. If others have any insights on this question, I'd be grateful for their input.

duhaime
  • 25,611
  • 17
  • 169
  • 224

2 Answers2

4

It looks like it removes everything up to and including the last comma.

^ means "starts with", .* means 0 or more occurrences of anything except a new line, and the comma just means a comma. In other words, it means: starting from the beginning of the string, look for any number of characters followed by a single comma. Then replace them with nothing (an empty string)

user3413723
  • 11,147
  • 6
  • 55
  • 64
  • 2
    I think `.*` is greedy so it will get the last comma- `"hello,there,buddy".replace(/^.*,/, '')` --> 'buddy' – Mark Jul 24 '17 at 02:05
  • Oh my word I didn't see the comma. Thank you. – duhaime Jul 24 '17 at 02:05
  • @user3413723 I have a bonus question: Do you know why one would do this to base64 encoded data? -- Ah, it's the file type! (e.g. `data:image/png;base64,iVBORw0KGgoAAAAN...`) – duhaime Jul 24 '17 at 02:06
  • 2
    @duhaime, it's a data url which has some metadata before the actual content you want. So it just strips that out. See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs – user3413723 Jul 24 '17 at 02:09
1

The RegExp replaces the MIME type portion of a data URL. The RegExp could also be composed as

var res = str.split(",")[1];
guest271314
  • 1
  • 15
  • 104
  • 177