[英]count a how many times a letter appears in javascript using indexOf
[英]expand a string in JavaScript to display letter and how many times that letter appears
編寫一個 function 接受一個字符串,其中字母組合在一起並返回新字符串,每個字母后跟它出現的次數。 示例:('aeebbccd') 應該生成 // 'a1e2b2c2d1'
function strExpand(str) {
let results = ""
for (let i = 0; i < str.length; i++) {
let charAt = str.charAt(i)
let count = 0
results += charAt
for (let j = 0; j < str.length; j++) {
if (str.charAt(j) === charAt) {
count++;
}
}
results += count;
}
return results;
}
使用輸入'aeebbccd'
我得到'a1e2e2b2b2c2c2d1'
而不是'a1e2b2c2d1'
這個 function 是在每個字符后面加上一個數字,就是這個字符在字符串中任意位置出現的次數。 你可以改為這樣做以獲得你想要的結果。
function strExpand(str) {
let output = "";
// Iterate through each character of the string, appending
// to the output string each time
for (let i = 0; i < str.length; i++) {
let count = 1;
// If the next character is the same, increase the count
// and increment the index in the string
while (str[i + 1] == str[i]) {
count++;
i++;
}
// Add the character and the count to the output string
output += str[i] + count;
}
return output;
}
為了完整起見,正則表達式怎么樣?
const pattern = /(.)\1*/g; // put a char that exists in a capture group, then see if it repeats directly after const s = 'aeebbccd'; var result = ''; for (match of s.match(pattern)) { let this_group = match; let this_len = match.length; result = result + this_group[0] + this_len; // get only the first letter from the group } console.log(result); // a1e2b2c2d1
這將有助於工作。 編輯:哈,我看到我遲到了:D,但仍然是解決該問題的不錯的功能方法。
/** * @param string to count * @return string $characterA$count. ex. abbccc -> a1b2c3 */ function toCharacterCountString(str) { return Array.from(new Set(str).values()).map(char => { return `${char}${(str.match(new RegExp(char, "g")) || []).length}`; }).join(''); } console.log(toCharacterCountString('abbccc')); // a1b2c3 console.log(toCharacterCountString('aeebbccd')); // a1e2b2c2d1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.