Home > Web Front-end > JS Tutorial > body text

JS function code for Chinese string interception_javascript skills

WBOY
Release: 2016-05-16 17:36:27
Original
1363 people have browsed it

In order to solve this problem, yesterday I wrote a function that intercepts strings based on the number of bytes.
The specific use is very simple, just use it like String.subString(start, end). For example: var str = "Hey, I will caress you"; var str1 = str.subCHStr(2, 2); var str2 = str.subCHString(2, 4); alert(str1 " == " str2);

Copy code The code is as follows:

Code
//Calculate the string length
String.prototype.strLen = function() {
var len = 0;
for (var i = 0; i < this.length; i ) {
if (this.charCodeAt(i) > 255 || this.charCodeAt(i) < 0) len = 2; else len ;
}
return len;
}
//Split the string into characters and store them in In the array
String.prototype.strToChars = function(){
var chars = new Array();
for (var i = 0; i < this.length; i ){
chars [i] = [this.substr(i, 1), this.isCHS(i)];
}
String.prototype.charsArray = chars;
return chars;
}
//Determine whether a character is a Chinese character
String.prototype.isCHS = function(i){
if (this.charCodeAt(i) > 255 || this.charCodeAt(i) < 0)
                                        return true; end){
var len = 0;
var str = "";
this.strToChars();
for (var i = 0; i < this.length; i ) {
if(this.charsArray[i][1])
len = 2;
else
len ;
if (end < len)
return str;
else if (start < len)
str = this.charsArray[i][0];
}
return str;
}
//Intercept string (intercepted from start byte length bytes)
String.prototype.subCHStr = function(start, length){
return this.subCHString(start, start length);
}


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!