当前位置:网站首页>限制输入字符长度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);返回的将是:你好啊...
边栏推荐
- 100002nd prime
- Interviewer: please name four ways to exchange the values of two variables without using third-party variables
- Blazor University (33)表单 —— EditContext、FieldIdentifiers
- Possible values for @supply in kotlin
- College Students' big factory road
- Win10 computer power management turns on excellence mode
- # 云原生训练营毕业总结
- A few simple ways for programmers to exercise their waist
- Pie chart metamorphosis record, the liver has 3000 words, collection is to learn!
- 版本管理工具使用
猜你喜欢

Scala Basics (II): variables and data types

数字商品DGE--数字经济的财富黑马

业务流程图设计

Remember a simple JVM tuning experience

Matlab|基于BP神经网络进行电力系统短期负荷预测

Share some remote office experience in Intranet operation | community essay solicitation

Problem solving process of no internet access

What is the sudden power failure of iPhone and how to solve it?

High availability in Internet three highs (high concurrency, high performance and high availability)

Eureka registration information configuration memo
随机推荐
Fastadmin applet assistant is purchased, but the work order cannot be published in the problem work order
PyQt theme
The programmer's eight-year salary change has made netizens envious: you pay me one year's salary per month
音视频与CPU架构
官方零基础入门 Jetpack Compose 的中文课程来啦!
Which SMS plug-in is easy to use? The universal form needs to be tested by sending SMS
[image filtering] image filtering system based on Matlab GUI [including Matlab source code 1913]
Prometeus 2.33.0 new features
使用 AnnotationDbi 转换 R 中的基因名称
为 ServiceCollection 实现装饰器模式
Is it safe to trade stocks with a compass? How does the compass trade stocks? Do you need to open an account
Breadth first traversal of Graphs
UTONMOS:以数字藏品助力华夏文化传承和数字科技发展
Introduction to bloc: detailed explanation of cube
High performance and high availability computing architecture based on microblog comments
Interviewer: please name four ways to exchange the values of two variables without using third-party variables
High availability in Internet three highs (high concurrency, high performance and high availability)
Matlab|基于BP神经网络进行电力系统短期负荷预测
基於鄰接矩陣的廣度優先遍曆
win32