2017-04-24 26 views
-3

如何在JavaScript中得到重複的字符,得到重複的字符在javascript

像輸入:

aaabcccdeffa

輸出:

a4bc3def2

+2

你有什麼試過?什麼樣的輸入?一個字符串,一個數組,一個文本框? – Weedoze

+0

歡迎來到StackOverflow!要獲得幫助,您應該提供[MCVE](https://stackoverflow.com/help/mcve)。這可以幫助其他人瞭解您正在嘗試做什麼,並向我們展示您已經嘗試過的內容。 – Chewtoy

回答

2

試試這個:

var str = "aaabcccdeffa"; // Original string 

// We are going to create a key-value array to store the number of occurance 
// per letter (eg. 'a' : 4, 'b' : 1 etc.) 
var store = {}; 

// Next we loop through each letter in the string 
for (var a in str) { 
    if (store[str[a]] == undefined) { // If this letter has not ben found before, we set the count to 1 (first occurance) 
    store[str[a]] = 1; 
    } 
    else { // else if the letter has been found, we increase the count by one 
    store[str[a]] += 1; 
    } 
} 

// At this point, we have a key value array that contains the count of each letter 

// Next, we loop through this array to generate the new string 
var newStr = ''; // Initialise new string 
for (var char in store) { 
    newStr += char; // append the letter to the string 
    if (store[char] > 1) { 
    newStr += store[char]; // If the count is more than one, we want to show the number too, so we append the number to the string 
    } 
} 

輸出將在newStr

1

這裏是使用jquery和正則表達式來計算字符的頻率的參考代碼。

// Variable Declaration with Source text 
var sourceText="aaabcccdeffa"; 
var resultText=""; 
// Splitting the source text to array 
var sourceTextArray=sourceText.split(""); 
var uniqueText = []; 
//Fetches Unique text from sourceTextArray in order 
$.each(sourceTextArray, function(i, el){ 
    if($.inArray(el, uniqueText) === -1) uniqueText.push(el); 
}); 
//Iteration with unique text array 
$.each(uniqueText, function(i, el){ 
//Regular Expression approach to calculate frequency of character with source text 
resultText+=(sourceText.match(new RegExp(el, "g")) || []).length>1?el+(sourceText.match(new RegExp(el, "g")) || []).length:el; 
}); 

alert(resultText); 

Working Example Here

2

你可以使用一個哈希表,這在javascript通過對象來完成。此代碼的作品

function duplicateCharacters(str) { 
    //Create an empty object 
    var hashTable = {}; 

    for(var i = 0; i < str.length; i++){ 
     //Check if the character has already been registered 
     //If false, register it and link a 1 to it 
     //If true, increment the integer linked to it 
     if (hashTable.hasOwnProperty(str[i])) 
      hashTable[str[i].toString()]++; 
     else 
      hashTable[str[i].toString()] = 1; 
    } 
    var output = ""; 
    //Go through the hashTable 
    for(var key in hashTable) { 
     //Concatenate the key 
     output += key.toString(); 
     //If the character only appeared once, do not add it 
     if(hashTable[key] != 1) 
      output += hashTable[key].toString() 
    } 
    return output; 
}