【Vue】实现显示输入框字符长度

文章讲述了如何使用JavaScript计算用户请求参数中提示字符串的字节长度,根据不同Unicode编码范围确定所需字节数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 <div style="float: right; margin-right: 10px">
      <el-popover placement="top-start" width="200" trigger="hover" :content="'当前输入的内容字节长度为:' +
        this.byteLength +
        ',剩余可输入的字节长度和最大文本长度设置的最大值为:' +
        (4096 - this.byteLength)
        ">
        <el-button slot="reference" type="text" class="el-icon-info"></el-button>
      </el-popover>
      <span style="line-height: 50px; font-size: 10px"> 字节长度: </span>

      <span style="line-height: 50px; font-size: 12px; color: #aaa">{{
        this.byteLength
      }}</span>
    </div>
computed: {
    byteLength() {
      var str = this.requestParams.prompt;
      if (str == null || str === undefined) return 0;
      if (typeof str != "string") {
        return 0;
      }
      var total = 0,
        charCode,
        i,
        len;
      for (i = 0, len = str.length; i < len; i++) {
        charCode = str.charCodeAt(i);
        if (charCode <= 0x007f) {
          total += 1; //字符代码在000000 – 00007F之间的,用一个字节编码
        } else if (charCode <= 0x07ff) {
          total += 2; //000080 – 0007FF之间的字符用两个字节
        } else if (charCode <= 0xffff) {
          total += 3; //000800 – 00D7FF 和 00E000 – 00FFFF之间的用三个字节,注: Unicode在范围 D800-DFFF 中不存在任何字符
        } else {
          total += 4; //010000 – 10FFFF之间的用4个字节
        }
      }
      return total;
    },
  },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值