![](/img/trans.png)
[英]Count the number of occurrences of a character in a string in Javascript
[英]How to count the number of each consecutive unique character of a string in javascript
如何計算字符串中每個連續唯一字符的數量。
Case exampe:
// Function Name : CountUniqueChar()
// Input : String
// Output : Array Object [{k: v}]
// Example :
// Input : “aaaasssiia”
// output : [{“a”: 4}, {“s”: 3}, {“i”: 2}, {“a”: 1}]
將matchAll()
與正則表達式和map()
:
const count = (s) => [...s.matchAll(/(.)\\1*/g)].map(([{length}, c]) => ({[c]: length})); console.log(count('aaaasssiia'));
使用for loop
遍歷字符串中的每個字符並與下一個字符進行比較以保持連續唯一字符的計數。
const input = "aaaasssiia"; const countChar = (str) => { const list = []; let count = 1; for (let i = 0; i < str.length; i++) { if (str[i] === str[i + 1]) { count++ } else { const obj = {}; obj[str[i]] = count; list.push(obj); count = 1; } } return list; } console.log(countChar(input))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.