I'm trying to check that a list of items is entered properly and includes a comma between each entry. In this list there can only be a single word and after every word there must be a comma.
I'm attempting to use a lookbehind to assert that there is a comma before every space, but it seems to only work for the first occurrence of the character. How can I look through the entire string?
const nameStringList = "Fozzie, Gonzo, Kermit Animal "
const isValid = /\s+/.test(nameStringList) && !(/(?<=,)\s.*/.test(nameStringList))
console.log(isValid);
/^(\S+(,\s|$))+$/
Explanation:
Match one or more non-whitespace characters followed by either a comma and a whitespace character or the end of the message. This should be repeated at least once but can be repeated more times. This should match from the start to the end of the message, so if part of the string doesn't match then it won't work.