[英]Find strings with words starting with specific character in an array
If I have array of string like如果我有像这样的字符串数组
const arrayOfString=["Ajay Choudhary","Charlli Chouhan","Kerri Cilce","Dalis Menary"];
How to get name which has startswith C and surname startswith C like my output will be如何获得以 C 开头的名字和以 C 开头的姓氏,就像我的 output 一样
Ajay Choudhary
Charlli Chouhan
Kerri Cilce
I have tried below but it does not give expected output我在下面尝试过,但没有给出预期的 output
const arrayOfString = ["Ajay Choudhary", "Charlli Chouhan", "Kerri Cilce", "Dalis Menary"]; arrayOfString.forEach(element => { //console.log(element); if (element.startsWith("C")) { //console.log(element); } if (element.charAt(element.charAt(-1)).startsWith("C")) { console.log(element); } });
You can use simple regex to check if any of words starts with C
:您可以使用简单的正则表达式来检查是否有任何单词以
C
:
const arrayOfString=["Ajay Choudhary","Charlli Chouhan","Kerri Cilce","Dalis Menary", "Karoline-Celvin Boobier"]; arrayOfString.forEach(element => { if (/\bC\w+/.test(element)) { console.log(element); } });
Filter on the letter.筛选字母。 I assume all names will start with capital letter
我假设所有名字都以大写字母开头
Note: McCain will be included too.注意:麦凯恩也将包括在内。
const arrayOfString = ["Ajay Choudhary", "Charlli Chouhan", "Kerri Cilce", "Dalis Menary"]; const cNames = arrayOfString.filter(name => name.includes("C")) console.log(cNames)
If you want to avoid names like McCain, then you can split and filter on startsWith如果你想避免像麦凯恩这样的名字,那么你可以在 startsWith 上拆分和过滤
const arrayOfString = ["Ajay Choudhary", "Charlli Chouhan", "Kerri Cilce", "Dalis Menary", "Noddy McCain"]; const cNames = arrayOfString.filter(name => name.split(" ").some(name => name.startsWith("C"))); // either first or lastname(s) starts with letter C console.log(cNames)
I think, spliting words with space and then filtering base on starting with 'C' will do what you want.我认为,用空格拆分单词,然后以“C”开头进行过滤会做你想做的。
here is what I did:这是我所做的:
arrayOfString.filter(name=>name.split(' ').filter(n => n.startsWith('C')).length > 0)
const arrayOfString = ["Ajay Choudhary", "Charlli Chouhan", "Kerri Cilce", "Dalis Menary"]; const result = arrayOfString.filter(name=>name.split(' ').filter(n => n.startsWith('C')).length > 0) console.log(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.