Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to calculate number of occurrence of character in string using jquery

Tags:

jquery

asp.net

I am having a textbox and i want to count number of occurrence of '.'

if textbox is already having a '.' then user is not allowed to type '.' from his key board

here is my code:

 $('.txt').keyup(function() {
            var ele = $(this).val();
            var contains = (ele.indexOf('.') > -1);
            if (contains) {
                var count = $(this).val().match(/./g);
                if (count > 1) {                    
                    var cont = $(this).val();
                    var str = $(this).val().length;

                    $(this).val(cont.substring(0, str));
                }                   
            }

        });

$(this).val().match(/./g) gives me index of occurrence of '.' but i want to count occurrences of it.

like image 568
Aijaz Chauhan Avatar asked Jul 09 '13 06:07

Aijaz Chauhan


Video Answer


2 Answers

You can use the below code to find the number of time a character "." occurs in a string.

    var regex = new RegExp(/\./g)
    var count = "This is some text .".match(regex).length;
like image 135
Anshuman Jasrotia Avatar answered Sep 30 '22 20:09

Anshuman Jasrotia


Your regex needs to be changed. "." in regex means everything. You need to escape the ".". Probably like this...

$(this).val().match(/\./g);
like image 30
mohkhan Avatar answered Sep 30 '22 19:09

mohkhan