count string length including 'invisible chara

2019-08-09 11:27发布

问题:

I am trying to display a "x characters left" text next to a textarea, to see how much still can be written, with javascript / jquery:

var area = 'textarea#zoomcomment';
var c = $(area).val().length;

Then the input is validated with laravel's max validation.

'comment' => 'required|max:3000'

The javascript does not count the \n or \r characters, but PHP/laravel does. Is there a javascript function to count everything , including linebreaks etc ? I'd like to have the same string length with js and php.

edit:

it seems, that javascript/jquery counts \n\r as 1 and php strlen() counts it as 2 characters. I tried to avoid jquery, but it still seemed to count wrong :(

        var c = document.getElementById('zoomcomment').value.length;
        alert(c);

this question has a good answer

回答1:

You could do it using html function which gives you innerhtml -

var area = 'textarea#zoomcomment';
var c = $(area).html().length;