当前位置:网站首页>限制输入字符长度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);返回的将是:你好啊...
边栏推荐
- Breadth first traversal of Graphs
- 2022-06-25: given a positive number n, it means that there are tasks 0~n-1. Given an array of length N, time[i] means the time when task I is completed. Given a two-dimensional array matrix, matrix[j]
- 基於鄰接矩陣的廣度優先遍曆
- 请指教同花顺开户选选择哪家券商比较好?网上开户是否安全么?
- Oracle练习
- Blazor University (33) form - editcontext, fieldidentifiers
- PyQt theme
- How to solve the problem that the iPhone 13 lock screen cannot receive the wechat notification prompt?
- IPhone 13 screen stuck black, unable to shut down? How to solve
- Technology is to be studied
猜你喜欢

Possible values for @supply in kotlin

Scala Basics (II): variables and data types

Pie chart metamorphosis record, the liver has 3000 words, collection is to learn!

多测师拱墅肖sir_工作目录下的use websocket报错解决方案

Cross server SQL connection configuration
![[image filtering] image filtering system based on Matlab GUI [including Matlab source code 1913]](/img/53/6683e7db960fbba773a9013985dcca.jpg)
[image filtering] image filtering system based on Matlab GUI [including Matlab source code 1913]

How to solve the problem that the iPhone 13 lock screen cannot receive the wechat notification prompt?

Redis Lua沙盒绕过命令执行(CVE-2022-0543)

【缺陷检测】基于matlab GUI印刷电路板自动缺陷检测【含Matlab源码 1912期】

Analytic hierarchy process
随机推荐
官方零基础入门 Jetpack Compose 的中文课程来啦!
df报错Stale file handle
Redis classic 20 questions
PyQt theme
Which SMS plug-in is easy to use? The universal form needs to be tested by sending SMS
Never criticize
使用 AnnotationDbi 转换 R 中的基因名称
[image filtering] image filtering system based on Matlab GUI [including Matlab source code 1913]
OA process editing
What is the sudden power failure of iPhone and how to solve it?
Redis Lua sandbox bypass command execution (cve-2022-0543)
Graduation summary of cloud native training camp
Cox 回归模型
基于邻接表的广度优先遍历
UTONMOS坚持“藏品、版权”双优原则助力传统文化高质量发展
表达式的动态解析和计算,Flee用起来真香
【系统架构】-如何评估软件架构
Cow sequencing problem
Multi surveyor Gongshu campus Xiao sir_ Page error in Jenkins
100002nd prime