谁能帮助我获取javascript中给定字符串中重复字符的计数。
例如,
"abccdef" -> 1 (Only "c" repeated)
"Indivisibilities" -> 2 ("i" and "s" repeated)
谢谢你
这是一个有趣的问题。我们可以做的是使用将字符串转换为小写String.toLowerCase
,然后在上分割""
,这样我们得到了一个字符数组。
然后,我们将对进行排序Array.sort
。排序后,我们将使用进行连接Array.join
。然后,我们可以使用正则表达式/(.)\1+/g
,这实际上意味着匹配一个字母和相同的后续字母。
当使用String.match
指定的正则表达式时,我们将得到一个数组,其长度就是答案。还用了一些try...catch
返回0
的情况下,比赛收益null
和结果TypeError
。
function howManyRepeated(str){
try{ return str.toLowerCase().split("").sort().join("").match(/(.)\1+/g).length; }
catch(e){ return 0; } // if TypeError
}
console.log(howManyRepeated("Indivisibilities")); // 2
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句