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

时光总嘲笑我的痴心妄想 提交于 2020-01-06 01:29:49

问题


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;


来源:https://stackoverflow.com/questions/33118612/count-string-length-including-invisible-characters-like-r-n-in-javascript-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!