Reputation: 287
Is it easily possible to use str.endsWith with multiple values? I have the next code:
var profileID = profile.id;
var abtest = profileID.endsWith("7");
{return abtest}
In this case I would like to check if profileID
ends with a: 1, 3, 5, 7 or 9. Only if it is true, i want abtest to return true.
I know I can do it like this:
if (profileID.endsWith("1") || profileID.endsWith("3") || profileID.endsWith("5")
|| profileID.endsWith("7") || profileID.endsWith("9"))
{return abtest}
}
But I would like to try a cleaner way if possible. Does anyone know how to?
Upvotes: 6
Views: 8502
Reputation: 72177
You can extract the last character of the string and check if it is included in an array that contains the desired values:
if (['1', '3', '5', '7', '9'].includes(profileID.substring(profileID.length - 1))) {
// ...
}
Upvotes: -1
Reputation: 5354
I'd say regex is better here:
if (/[13579]$/.test(profileID)) {
// do what you need to do
}
Upvotes: 7
Reputation: 14871
You could try .some
if (['1','3','5','7','9'].some(char => profileID.endsWith(char))) {
//...
}
Upvotes: 16