简体   繁体   中英

count Repeated characters

I want to count repeated characters in input order. Here is my code.

<textarea id="field"></textarea>
<input type="submit" name="sub" id="sub" value="GO" />
<div id="charNum"></div>

and

$("#sub").click(function () {
    var all = "abcdefghijklmnopqrstuvwxyz";
    var str = $("#field").val();
    var text = "";
    for (var i = 0; i < all.length; i++) {
        var char = all.charAt(i);
        if (str.split(char).length > 1) text += str.split(char).length - 1 + "<br>";
    }
    $("#charNum").html(text);
});

If I enter 'mmani' I get the output '1121' , it checks by alphabet order. I want output like this: '2111' .

Please have a look on the comments in the code for Explanation.

var k = "mamma mia miami".split('')

//if you want to exclude spaces
//var k = "mamma mia miami".split(/\s+/).join('').split('')

var p = {};
//count frequency of every character
for(var i=0;i<k.length;i++) {
    var currentChar = k[i];
    if(p[currentChar] == undefined) {
        //initialize counter for new char found
        p[currentChar]=1;
    } else {
        //increment counter for every next match for that char
        p[currentChar]++;
    }
}

var output = '';
//format output according to your need
for(each in p) {
    output += p[each]
}

It sounds like you're overcomplicating it, instead of looping over the entire alphabet, why not just loop over the characters in the value, and count the number of occurrences?

var charCount = {};
$.each(this.value.split(''), function(i, v) {
    charCount[v] = charCount[v] + 1 || 1; 
});

Here's a fiddle

A much cleaner way to do this is to just compare str.charAt(i) to str.charAt(i+1) :

for(var i=1; i<str.length; i++) {
    if(str.charAt(i) === str.charAt(i-1)) {

Demo fiddle

You may possibly try this example:

script

var duplicateCount = function(v)
{
    var out = document.getElementById("output");
    console.log("text is: " + v);
    v = v.split('');
    var map = {}, c, t;
    for(var i = 0, l = v.length; i < l; i ++)
    {
        c = v[i];
        t = 0;
        if(map[c])
        {
            t = map[c];
            map[c] = ++ t;
        }
        else
        {
            map[c] = 1;
        }
    }
    console.log(map);
    var arr = [];
    for(var k in map)
    {
        arr.push(map[k]);
    }
    out.value = arr.join('');
};

html

<input type="text" onkeyup="duplicateCount(this.value);" placeholder="Text here"/>
<input type="text" readonly="readonly" id="output"/>

Try This

$("#sub").click(function () {
        var uniqueOccurence = "";
        var str = $("#field").val();
        for (var i = 0; i < str.length; i++) {
            if(uniqueOccurence.indexOf(str.charAt(i)) < 0)
            uniqueOccurence += str.charAt(i);
        }

        var text = "";
        for (var i = 0; i < uniqueOccurence .length; i++) {
            var char = uniqueOccurence .charAt(i);
            if (str.split(char).length > 1) text += str.split(char).length - 1 + "<br>";
        }
        $("#charNum").html(text);
    });

This can be achieved with a regular Expression.

Solution:

$("#sub").click(function () {
    var str = $("#field").val();
    var text = str.match(/([a-z])\1?/g).map(function(a) {return a.length}).join('');

    $("#charNum").html(text); // Will be '2111'
});

What it does:

The regular expression matches every character ( [az] ) and all of it's repeating occurences ( \\1 references the first parentheses group, which contains the matched character), using the g flag to apply it to all of the string.

The returned value of this would be an array of the matches like this:

[ "mm", "a", "n", "i" ]

Mapping over these and replacing them with their length ( [ 2, 1, 1, 1 ] ), and then joining the returned string will yield the expected result: "2111"

Not sure how you would want to deal with occurences of >= 10 of the same characters, though.

Since Array.prototype.map is not supported in IE8 and below, here's a solution avoiding that function:

$("#sub").click(function () {
    var str = $("#field").val();
    var matches = str.match(/([a-z])\1?/g);
    var text = "";

    for(var i = 0; i < matches.length; i++) {
        text = text + matches[i].length;
    }

    $("#charNum").html(text); // Will be '2111'
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM