evilReiko
evilReiko

Reputation: 20473

JS/jQuery: how many character occurance in textarea

Assuming: str value = 'This is some text';

I want to count how many 't' occurrences, how to do that?

Upvotes: 3

Views: 2303

Answers (7)

Arun P Johny
Arun P Johny

Reputation: 388316

It is much easier with regex

var regex = new RegExp("t", "gi")
var count = "This is some text".match(regex).length;

Will give you counts of t in the given string(ignore case).

You can test it here.

Further reference
RegExp 1
RegExp 2
String
String.match()

Upvotes: 9

Bence Olah
Bence Olah

Reputation: 684

<button onclick="alert(countCharacter('abcdea', 'a'));"> Test! </button>

<script type="text/javascript">
    function countCharacter(sample, characterToFind) {
        var result = 0;

        for(i = 0;i<sample.length;i++) {
            if(sample[i] === characterToFind) {
                result++;
            }
        }

        return result;
    }
</script>

Upvotes: 0

Wasim Karani
Wasim Karani

Reputation: 8886

May be can help you here

.replace().length

with regards

Wazzy

Upvotes: 0

Shadow Wizard
Shadow Wizard

Reputation: 66389

var sValue = 'This is some text';
var tCount = sValue.split("t").length - 1;
alert("t appears " + tCount + " times");

If you want to count occurrences of all letters, you better use one loop as shown in the other answers.

Upvotes: 4

user356808
user356808

Reputation:

I think you all make it more complicated than it needs to be. Use regex. This is also case insensitive. If you want case sensitive, remove the i after g.

var str = "This is some text";
var pattern = /t/gi;
alert(str.match(pattern).length);

Make it shorter.

var str = "This is some text";
alert(str.match(/t/gi).length);

Upvotes: 1

btx
btx

Reputation: 266

Several ways to do this...

function countChar(str, searchChar) {
   var num=0;
   for (var i=0; i<str.length; ++i) {
      if (str[i] == searchChar)
         ++num;
   }
   return num;
}

use like:

numt = countChar('This is some text', 't');

Upvotes: 0

spolu
spolu

Reputation: 660

An easy solution is to loop

var count = 0;
for(var i = 0; i < str.length; i ++) {
  if(str.charAt(i) === 't')
    ++count;
}

You might also want to use str.toLowerCase(); if you don't want to be case sensitive.

Upvotes: 1

Related Questions