当前位置:网站首页>限制输入字符长度length英文1个字符中文2个字符
限制输入字符长度length英文1个字符中文2个字符
2022-06-26 01:45:00 【xyphf_和派孔明】
js虽然提供了计算字符串所占字节数的函数,但是却不能正确计算汉字所占的字节数,如document.form1.username.value=“你好啊上海”,document.form1.username.value.length返回的是5而不是10,于是给编程时带来一些麻烦,如限制固定长度字符的输入,截取固定长度的字符串都因为这个问题达不到预想的效果,下面是自己写的一个简单的函数,用于截取固定长度的字符串,中英文都适用.
// js截取字符串,中英文都能用
// 如果给定的字符串大于指定长度,截取指定长度返回,否者返回源字符串。
cutstr(str,len) {
var str_length = 0;
var str_len = 0;
var str_cut = new String();
var str_len = str.length;
for(var i = 0;i<str_len;i++)
{
var a = str.charAt(i);
str_length++;
if(escape(a).length > 4)
{
//中文字符的长度经编码之后大于4
str_length++;
}
str_cut = str_cut.concat(a);
if(str_length>=len)
{
str_cut = str_cut.concat("...");
return str_cut;
}
}
//如果给定字符串小于指定长度,则返回源字符串;
if(str_length<len){
return str;
}
},如cutstr("你好啊上海",6);返回的将是:你好啊...
边栏推荐
- The programmer's eight-year salary change has made netizens envious: you pay me one year's salary per month
- Simplex method (1)
- How to check and cancel subscription auto renewal on iPhone or iPad
- 程序员的八年工资变动,令网友羡慕不已:你一个月顶我一年工资
- Possible values for @supply in kotlin
- How to open a stock account? Is it safe to open an account online?
- OpenAPI 3.0 规范-食用指南
- 【机器学习】基于多元时间序列对高考预测分析案例
- Technology is to be studied
- 多测师拱墅肖sir_工作目录下的use websocket报错解决方案
猜你喜欢

UTONMOS:以数字藏品助力华夏文化传承和数字科技发展

Possible values for @supply in kotlin

基于邻接矩阵的广度优先遍历
![[machine learning] case study of college entrance examination prediction based on multiple time series](/img/13/7368a169d07e01d86a2d2c0207ccca.png)
[machine learning] case study of college entrance examination prediction based on multiple time series

图的广度优先遍历

Pointnet/pointnet++ learning

Dynamic analysis and calculation of expression, flee is really sweet to use

如何在 R 中的绘图中添加回归方程

Scala Basics (II): variables and data types

Termux install openssh
随机推荐
Consumer of microservices
股票开户怎么开户?网上开户是否安全么?
官方零基础入门 Jetpack Compose 的中文课程来啦!
How to solve the problem that the iPhone 13 lock screen cannot receive the wechat notification prompt?
High performance and high availability computing architecture based on microblog comments
Unexpected output super efficiency SBM model matlab code
A high-frequency interview question from a large factory: tell me about the solution of high and low interface idempotence? Solutions are attached.
程序员的八年工资变动,令网友羡慕不已:你一个月顶我一年工资
【系统架构】-如何评估软件架构
Termux install openssh
Share some remote office experience in Intranet operation | community essay solicitation
MySQL必須掌握4種語言!
Pointnet/pointnet++ learning
Possible values for @supply in kotlin
Cross server SQL connection configuration
多测师拱墅校区肖sir_jenkins中搭建出现页面报错
Graduation summary of cloud native training camp
Thirty ninth step
Depth first traversal based on adjacency table
2022年挖财商学院证券开户安全嘛?