Regex To Match Comma Before & After A String

A regular expression that allows you to match any comma before and/or after a string. Can be useful for removing all unexpected commas in an array.

Comma Before A String:

/^,|,$/

Matches:

  • ,regex,pattern,com
  • ,,regex,pattern,com

Comma Before And After A String:

/^,+|,+$/

Matches:

  • ,regex,pattern,com
  • regex,pattern,com,
  • ,,regex,pattern,com,

Has Whitespace:

/^[,\s]+|[\s,]+$/

Matches:

  • , regex, pattern, com
  • ,, regex, pattern, com

See Also: