2016-03-26 29 views
-1

Boşluk içeren bir dizenin içindeki tüm "," yi kaldırmaya çalışıyorum.ile ilgili sorunlar .replace()

// function for getting the frequency of each word within a string 
function getFreqword(){ 
    var string = tweettxt.toString(), // turn the array into a string 
     split = string.split(" "), // split the string 
     words = {}; 

    for (var i=0; i<split.length; i++){ 
    if(words[split[i]]===undefined){ 
     words[split[i]]=1; 
    } else { 
     words[split[i]]++; 
    } 
    } 
    return words; 
} 

döndürür:

{ hello: 50, bye: 36, 'bye,hello': 6 } 

bir girişim 'Merhaba, kal' oluşumunu ortadan kaldırmak için, şu anda aşağıdaki tweettxt sadece Merhaba birden çok örneği ile bir dizi kodu ve güle sahip Ben rastladım ve on line yerine .split ait .Kapağı uygulanan 4 split = string.replace(/,/g, "") ancak bu daha sonra döndürür:

{ h: 56, e: 98, l: 112, o: 56, ' ': 91, b: 42, y: 42 } 

Benim anlayış olduğunu .Kapağı olur sadece temsilcisi "" ile dantel, ama bu durum böyle değil. Herhangi biri yardım sunabilir mi?

DÜZENLEME:

kodu (/,/g "") String.Replace

// function for getting the frequency of each word within a string 
function getFreqword(){ 
    var string = tweettxt.toString(), // turn the array into a string 
     split = string.replace(/,/g, ""), // split the string 
     words = []; // array for the words 

    for (var i=0; i<split.length; i++){ 
    if(words[split[i]]===undefined){ 
     words[split[i]]=1; 
    } else { 
     words[split[i]]++; 
    } 
    } 
    return words; 
} 
+1

'. – Xufox

+0

Bu '.replace() 'kodunu kodunuza tam olarak koymaya çalıştınız - lütfen sorunuzun içinde yer alınız. '.replace()' bir dizede çalışır ve yeni bir dize nesnesi döndürür. – jfriend00

+1

Dize gibi kelimeler kullanmak ve değişken adlar olarak bölmek için iyi bir uygulama değildir. Tweettxt'i doğrudan kullanamaz mısınız? – MikeC

cevap

2

.replace sadece virgül olmadan aynı dize (değil dizi) döndürür. Ayrıca, sözcük tabanlı od boşlukları saymanız gerekiyorsa, virgülleri boşluklarla ("") değiştirmeniz gerekir. İlk önce virgüllerin yerini almanız ve sonra bölüşmeniz gerekir. buna göre mantık ayarlamak zorunda, bir dize döndürür replace` bir dizi, `döndürür split` Örn .:

function getFreqword(){ 
var string = tweettxt.toString(), // turn the array into a string 
    sanitizedString = string.replace(/,/g, " "), 
    split = sanitizedString.split(" "), // split the string 
    words = {}; 

    for (var i=0; i<split.length; i++){ 
     if(words[split[i]]===undefined){ 
      words[split[i]]=1; 
     } else { 
      words[split[i]]++; 
     } 
    } 
    return words; 
} 
+0

Bir çekicilik Kelime, Teşekkür ederim – user4357505