Job Smith
Job Smith

Reputation: 263

can someone help to explain this regular expression in javascript?

This code is used to get rid of mime type from rawdata.but I can not understand how it works

 content.replace(/^[^,]*,/ , '')

it seems quite different from java.... any help will be appreciated.

Upvotes: 1

Views: 1376

Answers (3)

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

The first thing you need to know is that there are regex literals in JavaScript, constructed by pairs of slashes. So like "..." is a string, /.../ is a regex. That's actually the only difference your code shows as compared to a Java regex.

Then, [abc] within a regex is called a character class, meaning "one character out of a, b or c". Conversely, [^abc] is a negated character class, meaning "one character except a, b or c".

So your sample means:

/     # Start of regex literal
^     # Start the match at the start of the string
[^,]* # Match any number of characters except commas
,     # Match a comma
/     # End of regex literal

Upvotes: 2

dano
dano

Reputation: 1043

The regular expression is the text between the two forward slashes, the first carat (^) means at the begining of the string, the brackets mean a character class, the carat inside the brackets means any character except a comma, then asterisk after the closing bracket means match zero or more of the character defined by the character class (which again is any character except the comma), and then finally the last comma means match the comma after all this. Then its used in a replace function so the matching result will be replaced with the second parameter, in your case: an empty string.

Basically it matches the first characters up to and including the first comma in the 'content' variable and then replaces it with an empty string.

Upvotes: 1

Dennis
Dennis

Reputation: 14455

Your mime-type probably is seperated by a comma , and at the beginning of your raw data. This regex says take everything from the beginning (^) that is NOT a comma ([^,]*) (the star makes it as many characters until there is a comma) and take the comma itself (,). Then replace it by nothing (''). This one only gets the first appearence because it is marked by the beginning ^ that it must be at the beginning of the string.

Upvotes: 2

Related Questions