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?
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?
Share Improve this question asked Sep 14, 2020 at 9:00 SybrentjuhSybrentjuh 2875 silver badges16 bronze badges 2 |3 Answers
Reset to default 16You could try .some
if (['1','3','5','7','9'].some(char => profileID.endsWith(char))) {
//...
}
I'd say regex is better here:
if (/[13579]$/.test(profileID)) {
// do what you need to do
}
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))) {
// ...
}
(Number(profileID) % 2) === 1
– zerkms Commented Sep 14, 2020 at 9:01((parseInt(profileID.slice(-1)) % 2) === 1)
– acbay Commented Sep 14, 2020 at 9:07