Next, go to the string section above and proceed to the section in the following table.
Format |
Camelize | capitalize | underscore | dasherize | inspect |
Deformation |
Toarray | succ | times |
One useful method here is inspect. According to the instructions in the reference manual, this function is to "return the representation of the string for debugging (that is, it is included in single or double quotation marks, and use '\' to escape special characters). This method is also involved in the object's tojson.
Since the characters to be escaped are involved, we naturally need an escape character information, which is directly given below:
String.specialChar = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'\\': '\\\\'
}
[In JSON. JS, there is an additional '"', because the string in JSON cannot contain", so escape is required]
The first step is to replace the special escape characters. The initial version is as follows:
function inspect() {
return this.replace(/[\b\t\n\f\r\\]/,function(a){
return String.specialChar[a];
});
}
For JSON format, double quotation marks are required. Therefore, we should be able to select our own return form. Therefore, a parameter usedoublequotes is provided for inspect, which returns strings with single quotation marks by default.
function inspect(useDoubleQuotes) {
var escapedString = this.replace(/[\b\t\n\f\r\\]/,function(a){
return String.specialChar[a];
});
if (useDoubleQuotes){
return '"' + escapedString.replace(/"/g, '\\"') + '"';
}
return "'" + escapedString.replace(/'/g, '\\\'') + "'";
}
This is similar to the functions in the source code, but the implementation method in prototype source code is not like this. The main difference is that escapedstring. All control characters are directly listed in the source code, which are expressed as [\ x00-\ x1f], and '\' is [\ x00-\ x1f \]. therefore, the above initial version is:
function inspect(useDoubleQuotes) {
var escapedString = this.replace(/[\x00-\x1f\\]/g, function(character) {
if (character in String.specialChar) {
return String.specialChar[character];
}
return character ;
});
if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
return "'" + escapedString.replace(/'/g, '\\\'') + "'";
}
Appendix, ASCII character encoding table, corresponding to \ x00-\ x1f:
If you find that. in specialchar, there are other control characters. One step in the source code is to convert the control character to the Unicode representation, because this method itself is to obtain the string form.
For example, vertical tab '\ V '. '\ V'. Inspect () -->' \ u000b'
Full version:
function inspect(useDoubleQuotes) {
var escapedString = this.replace(/[\x00-\x1f\\]/g, function(character) {
if (character in String.specialChar) {
return String.specialChar[character];
}
return '\\u00' + character.charCodeAt().toPaddedString(2, 16);
});
if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
return "'" + escapedString.replace(/'/g, '\\\'') + "'";
}
Topaddedstring (length [, Radix ])Number
The object to be converted to a string. If the length of the converted string is smallerlength
The specified value.0
Fill in the remaining digits on the left. Optional parametersradix
Used to specify the hexadecimal format used for conversion. This is an extension of number in prototype.
So '\ V '. charcodeat (). topaddedstring (2, 16) is to convert the character encoding of '\ V' to a two-digit hexadecimal encoding character. [The Operation character range is unlimited, so it will not exceed]. start with '\ u00.
Method description:
Toarray: Splits a string into character arrays.
Succ: converts the final character of a string to a subsequent character based on the Unicode alphabet
Times: Repeat the string.
The specific implementation is also very simple. The importance of the string part lies in the subsequent scripts, JSON and replacement processing. Others are enhanced.
function toArray() {
return this.split('');
}
Here, split ('') splits the string into a single character and returns it as an array. If you want to enhance it, you can give a parameter to toarray to specify the delimiter.
function toArray(pattern) {
return this.split(pattern);
}
console.log(toArray.call('my name is xesam',' '));//["my", "name", "is", "xesam"]
It is just the use of split, but it is not in the source code, because it is not necessary.
function succ() {
return this.slice(0, this.length - 1) + String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
}
The fromcharcode and charcodeat methods are used here. From the code, we can also see that the obvious difference between the two is that fromcharcode is a string static method, while charcodeat is a string method (hanging above string. Prototype ). Then the two are the opposite, the following is the http://www.w3school.com.cn to explain:
Fromcharcode () accepts a specified Unicode value and returns a string.
The charcodeat () method returns the Unicode encoding of characters at the specified position. The returned value is an integer between 0 and 65535.
Take the string 'Hello xesam' as an example to obtain all the characters except the ending character 'Hello xesasa ', add a character 'n' next to 'M' in the Unicode table. Therefore, the result is 'Hello xesance'
To print all the letters from 'A' to 'Z', use the following function:
function printChar(start,end){
var s = (start + '').charCodeAt()
var e = (end + '').charCodeAt();
if(s > e){
s = [e,e=s][0];
}
for(var i = s ;i <= e; i++){
console.log(String.fromCharCode(i));
}
}
printChar('a','z');
function times(count) {
return count < 1 ? '' : new Array(count + 1).join(this);
}
Times repeats the entire string. The main idea is to use the current character as the connector of the array to call join to obtain the expected results. Of course, you can add them in a loop, but it is not so concise.
To repeat each character in a string, you can use the same idea:
String.prototype.letterTimes = function(count){
var arr = [];
arr.length = count + 1;
return this.replace(/\w/g,function(a){
return arr.join(a);
})
}
console.log('xesam'.letterTimes(3));//xxxeeesssaaammm
Camelize | capitalize | underscore | dasherize is mainly about variable name conversion.
Camelize: converts a string separated by a horizontal line to the camel format.
Capitalize: converts the first letter of a string to uppercase, and all other letters to lowercase.
Underscore: converts a string in the form of camel to the following line ("_"
.
Dasherize: replace all the underlines in the string with the horizontal line ("_"
Replace"-"
).
Most obviously, it can be used in the mutual conversion between CSS attributes and Dom style attributes [class and float do not belong to this category ]. In the method above, you can use the came e method to convert the CSS attribute to the style attribute of the corresponding Dom, but this method is not used in turn, therefore, the underscore-> dasherize method must be called consecutively.
function camelize() {
return this.replace(/-+(.)?/g, function(match, chr) {
return chr ? chr.toUpperCase() : '';
});
}
The core is the use of the replace method. Others are quite simple. For more information, see the application of the string replace method.
function capitalize() {
return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
}
Note that the charat () method returns characters at the specified position .) The difference with charcodeat is enough.
function underscore() {
return this.replace(/::/g, '/')
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
.replace(/([a-z\d])([A-Z])/g, '$1_$2')
.replace(/-/g, '_')
.toLowerCase();
}
Instance to describe the steps:
'helloWorld::ABCDefg'.underscore()
//'helloWorld::ABCDefg'
.replace(/::/g, '/') //'helloWorld/ABCDefg'
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')//helloWorld/ABC_Defg
.replace(/([a-z\d])([A-Z])/g, '$1_$2') //hello_World/ABC_Defg
.replace(/-/g, '_') //hello_World/ABC_Defg
.toLowerCase(); //hello_world/abc_defg
This method is only applicable to the camel format, that is, it must have a 'fengfeng '.
function dasherize() {
return this.replace(/_/g, '-');
}
This is simply a replacement of characters.
For more information, see http://www.cnblogs.com/xesam /]
Address: http://www.cnblogs.com/xesam/archive/2012/01/11/2318351.html