2011-11-03 90 views

回答

6

使用一個正則表達式,然後匹配的數量可以從返回的數組中找到。這是使用正則表達式的幼稚方法。

'fat cat'.match(/at/g).length 

爲了防止在字符串不匹配的情況下,使用:

('fat cat'.match(/at/g) || []).length 
1

這裏:

function count(string, substring) { 
    var result = string.match(RegExp('(' + substring + ')', 'g')); 
    return result ? result.length : 0; 
} 
+0

那是我最初的刺它,但不幸的是,如果'substring'包含特殊字符的正則表達式,這將無法正常工作。例如:'count('計數期間','。')'會返回'18'。調用者必須知道這樣調用它:'count('計算句點','\。')' – Jacob

+0

@Jacob,在構建RegExp對象之前,您可以從子字符串中轉義RegExp元字符,例如,像這樣:'substring.replace(/ [[\] {}()* +?。\\ |^$ \ - ,&#\ s]/g,「\\ $&」)'... – CMS

+0

是的,你可以。儘管如此,對字符串使用'indexOf'可能更直接; RegExp對於這類任務來說是過分的,並且可能因此而變慢。 – Jacob

0

可以使用indexOf在一個循環:

function count(haystack, needle) { 
    var count = 0; 
    var idx = -1; 
    haystack.indexOf(needle, idx + 1); 
    while (idx != -1) { 
     count++; 
     idx = haystack.indexOf(needle, idx + 1); 
    } 
    return count; 
} 
0

不要使用它,它是過度複雜編輯:

function count(sample, searchTerm) { 
    if(sample == null || searchTerm == null) { 
    return 0; 
    } 

    if(sample.indexOf(searchTerm) == -1) { 
    return 0; 
    } 

    return count(sample.substring(sample.indexOf(searchTerm)+searchTerm.length), searchTerm)+1; 
} 
+0

你能解釋一下嗎? – methuselah

0
function count(str,ma){ 
var a = new RegExp(ma,'g'); // Create a RegExp that searches for the text ma globally 
return str.match(a).length; //Return the length of the array of matches 
} 

然後調用它,你在你的例子做的方式。 count('fat math cat','at');

0

您可以使用split也:

function getCount(str,d) { 
    return str.split(d).length - 1; 
} 
getCount("fat math cat", "at"); // return 3 
相關問題