计算字符串长度,包括“隐形字符",例如javascript和php中的\ r \ n [英] count string length including 'invisible characters' like \r \n in javascript and php

查看:324
本文介绍了计算字符串长度,包括“隐形字符",例如javascript和php中的\ r \ n的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在textarea旁边显示剩余x个字符"文本,以查看可以用javascript/jquery编写多少内容:

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;

然后使用laravel的max验证对输入进行验证.

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

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

javascript不计算\n\r字符,但是PHP/laravel计数.是否有JavaScript函数可以计算所有内容,包括换行符等?我想让js和php具有相同的字符串长度.

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.

看来,javascript/jquery将\n\r计为1,而php strlen()将其计为2字符.我试图避免使用jquery,但它似乎仍然算错了:(

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);

此问题有很好的答案

推荐答案

您可以使用html函数来实现,它会为您提供innerhtml-

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

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

这篇关于计算字符串长度,包括“隐形字符",例如javascript和php中的\ r \ n的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆