最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use endsWith with multiple values? - Stack Overflow

programmeradmin5浏览0评论

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 (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
Add a comment  | 

3 Answers 3

Reset to default 16

You 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))) {
  // ...
}
发布评论

评论列表(0)

  1. 暂无评论