I'm trying to validate a list of email addresses client-side. These addresses are separated by a comma or a semi-colon. They typically look like this:
'[email protected]; [email protected]; '
'[email protected], [email protected]'
I'm using a regular expression to split the string (I know how to validate each email address separately):
var separator = /[;,]+/;
var emails = value.split(separator);
I want to be able to remove the last separator if there is one. Server-side in python I'm doing something like that:
data = data.rstrip(separator)
value_list = re.split(separator, data)
With separator being the desired regexp.
My question is: how do I do this in Javascript ? More broadly, how do I remove the last characters of a string if they match a regexp ?
Rstrip can be done using end line $
symbol in the regex for .replace()
method. I have also changed your regular expression so that it can additionally remove spaces.
var separator = "[; ,]+",
emails = value.replace(new RegExp(separator + "$"), "")
.split(new RegExp(separator));
console.log(emails);