2015-07-12 145 views
-3

我是JavaScript新手,我正在嘗試編寫一個函數,該函數返回字符串中給定字符的出現次數。編寫函數來計算字符串中字符的出現次數。 [JavaScript]

到目前爲止,我已經得到了,

var str = "My father taught me how to throw a baseball."; 
var count = (str.match(/t/g) || []).length; 
alert(count); 

,如果我在JavaScript亞軍運行它,它的工作原理,但我不知道如何將它寫入的功能。有什麼建議麼?

+0

你甚至嘗試瞭解該語言的基礎知識嗎? – Saravana

回答

0
var str = "My father taught me how to throw a baseball."; 
var getCount=function(str){ 
    return (str.match(/t/g) || []).length; 
}; 
alert(getCount(str)); 
+0

正是我在找的東西。謝謝=) –

0
function getOccurencies(b){ 
var occur = {}; 
    b.split('').forEach(function(n){ 
    occur[n] = b.split('').filter(function(i){ return i == n; }).length; 
    }); 
    return occur; 
} 

getOccurencies('stackoverflow is cool') // Object {s: 2, t: 1, a: 1, c: 2, k: 1…} 
0

你談論的是:

function len(inputString) { 
    return (inputString.match(/t/g) || []).length; 
} 

這是你如何在JS創建功能的一種方式。開始的好點是here

請記住,JavaScript有更多的「創造」功能的一種方式。

2

試試這個 - 不使用正則表達式,因爲他們可以是一個痛苦,那麼爲什麼使用它們,除非你有

var str = "My father taught me how to throw a baseball."; 

function getCount=function(haystack, needle) { 
    return haystack.split(needle).length - 1; 
} 

alert(getCount(str, 't')); 

如果你想用正則表達式的解決方案

var str = "My father taught me how to throw a baseball."; 

function getCount=function(haystack, needle) { 
    var re = new RegExp(needle, 'g'); 
    return (haystack.match(re) || []).length; 
} 

alert(getCount(str, 't')); 

但你需要小心你正在尋找什麼needles,例如,. ({ [ ] }) !^$只是一些使用RegExp版本會導致問題的字符 - 但搜索字母數字(az,0-9)應該是安全的

相關問題