JS / jQuery: how many characters in the text area

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

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

+3
source share
7 answers

It is much easier with regex

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

Gives you the amount tin a given line (ignore case).

You can test it here .

Additional link
RegExp 1
RegExp 2
String
String.match ()

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

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

+4
source

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

str.toLowerCase();, .

+2

I think you are complicating things with what this should be. Use regex. It is also case insensitive. If you need a register with a register, delete me 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);
+1
source

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 as:

numt = countChar ("This is text", "t");

0
source
<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>
0
source

Maybe you can help here.

.replace().length

taking into account

Wazzy

0
source

Source: https://habr.com/ru/post/1783399/


All Articles