简体   繁体   中英

count string length including 'invisible characters' like \r \n in javascript and php

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM