“JavaScript Count Occurrences of Word in String” Réponses codées

JavaScript Count Occurrences of Letter in String

function count(str, find) {
    return (str.split(find)).length - 1;
}

count("Good", "o"); // 2
DenverCoder1

compter les occurrences de caractère en javascript de chaîne

var temp = "This is a string.";
var count = (temp.match(/is/g) || []).length;
console.log(count);

Output: 2

Explaination : The g in the regular expression (short for global) says to search the whole string rather than just find the first occurrence. This matches 'is' twice.
Ankur

JavaScript Count Occurrences in String

function countOccurences(string, word) {
   return string.split(word).length - 1;
}
var text="We went down to the stall, then down to the river."; 
var count=countOccurences(text,"down"); // 2
Grepper

La chaîne JS inclut le nombre

/** Function that count occurrences of a substring in a string;
 * @param {String} string               The string
 * @param {String} subString            The sub string to search for
 * @param {Boolean} [allowOverlapping]  Optional. (Default:false)
 *
 * @author Vitim.us https://gist.github.com/victornpb/7736865
 * @see Unit Test https://jsfiddle.net/Victornpb/5axuh96u/
 * @see http://stackoverflow.com/questions/4009756/how-to-count-string-occurrence-in-string/7924240#7924240
 */
function occurrences(string, subString, allowOverlapping) {

    string += "";
    subString += "";
    if (subString.length <= 0) return (string.length + 1);

    var n = 0,
        pos = 0,
        step = allowOverlapping ? 1 : subString.length;

    while (true) {
        pos = string.indexOf(subString, pos);
        if (pos >= 0) {
            ++n;
            pos += step;
        } else break;
    }
    return n;
}
Glamorous Gharial

JavaScript Count Occurrences of Word in String

kamlesh is good boy and good programmer
Concerned Crab

Réponses similaires à “JavaScript Count Occurrences of Word in String”

Questions similaires à “JavaScript Count Occurrences of Word in String”

Plus de réponses similaires à “JavaScript Count Occurrences of Word in String” dans JavaScript

Parcourir les réponses de code populaires par langue

Parcourir d'autres langages de code