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.
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;
                        Your regex needs to be changed. "." in regex means everything. You need to escape the ".". Probably like this...
$(this).val().match(/\./g);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With