Prototype source code analysis String part 2 _ prototype

Source: Internet
Author: User
Tags control characters
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:

The Code is as follows:


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:

The Code is as follows:


Function inspect (){
Return this. replace (/[\ B \ t \ n \ f \ r \]/, function (){
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.

The Code is as follows:


Function inspect (useDoubleQuotes ){
Var escapedString = this. replace (/[\ B \ t \ n \ f \ r \]/, function (){
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:

The Code is as follows:


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, '\ '') + "'";
}
[Html]
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:
[Code]
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]) converts the current Number object to a string. If the length of the converted string is smaller than the value specified by length, use 0 to fill in the remaining digits on the left. The optional parameter radix is 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.

The Code is as follows:


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.

The Code is as follows:


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.

The Code is as follows:


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:

The Code is as follows:


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 ');


The Code is as follows:


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:

The Code is as follows:


String. prototype. letterTimes = function (count ){
Var arr = [];
Arr. length = count + 1;
Return this. replace (/\ w/g, function (){
Return arr. join ();
})
}
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 a series of words separated by an underscore.
Dasherize: replace all the underlines in the string with hyphens "-").
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.

The Code is as follows:


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.

The Code is as follows:


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.

The Code is as follows:


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:

The Code is as follows:


'Helloworld: abcdefg'. underscore ()
// 'Helloworld: abcdefg'
. Replace (/:/g, '/') // 'helloworld/abcdef'
. 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 '.

The Code is as follows:


Function dasherize (){
Return this. replace (/_/g ,'-');
}


This is simply a replacement of characters.
From hillstone
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.