Prototype source analysis string part (ii) _prototype

Source: Internet
Author: User
Tags chr control characters join
Format Camelize |  Capitalize |  Underscore | Dasherize | Inspect
Deformation ToArray | SUCC | times
A useful method in this is inspect, as described in the reference manual, his role is "to return the string representation of the strings for debugging (that is, to include in single or double quotes and to escape using ' \ ' for special characters), and this method is also involved in the Tojson of object.

Since it involves characters that need to be escaped, we naturally want an escape character message, which is given directly below:
Copy Code code as follows:

String.specialchar = {
' \b ': ' \\b ',
' t ': ' \\t ',
' \ n ': ' \\n ',
' \f ': ' \\f ',
' \ r ': ' \ R ',
'\\': '\\\\'
}

"In the json.js, there is a" ", because the inside of the JSON string is not appear", so you need to escape the "

The first step, of course, is to replace the special escape character, the original version:
Copy Code code as follows:

function Inspect () {
Return This.replace (/[\b\t\n\f\r\\]/,function (a) {
return String.specialchar[a];
});
}

Double quotes are required for JSON forms, so we should be able to choose our own return form, so give inspect a parameter usedoublequotes, by default, return the string in single quotes.
Copy Code code as follows:

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, ' \\\ ') + "";
}

Now this is similar to the function of the source code, but the implementation of prototype source code is not like this, the main difference is escapedstring this paragraph. Source code directly lists all the control characters, expressed as [\x00-\x1f], plus ' \ ' is [\x00-\x1f\\], so the original version of the transformation above is:
Copy Code code 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]
Enclosed, ASCII control character encoding table, corresponding to \x00-\x1f:


If you find in addition to the characters in the String.specialchar, there are other control characters, the source code also has a step, that is, the control character into a Unicode representation, because the method itself is to obtain the form of a string.
such as 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, ' \\\ ') + "";
}

where Topaddedstring (length[, Radix]) converts the current number object to a string, and if the converted string length is less than the value specified by length, the remaining digits are replenished on the left with 0. The optional parameter radix is used to specify the system to use when converting. This is an extension of number in prototype and can be known for a while.
So ' \v '. charCodeAt (). topaddedstring (2, 16) is a two-bit encoder that converts the character encoding of ' \v ' into a 16-digit code [the action character will not be limited in scope, so it will not go beyond], and it will be preceded by ' \u00 '.

Method Description:
ToArray: Splits a string into a character array.
SUCC: The last character of the string converted from the Unicode alphabet to a subsequent character
Times: Repeats the string.
The corresponding implementation is also simple, and the important part of the string is the subsequent script, JSON, and substitution processing, all of which are of an enhanced nature.
Copy Code code as follows:

function ToArray () {
Return This.split (");
}

Where split (") is the string to be cast as a single character, and returned as an array, if you want to enhance, you can give a parameter to ToArray to specify the separator.
Copy Code code as follows:

function ToArray (pattern) {
return This.split (pattern);
}
Console.log (Toarray.call (' My name is Xesam ', ');//["I", "name", "is", "Xesam"]

Is the use of split, but the source code does not do so, because it is not necessary.

Copy Code code as follows:

function succ () {
Return This.slice (0, this.length-1) + String.fromCharCode (this.charcodeat (this.length-1) + 1);
}

The main thing here is the use of fromCharCode and charCodeAt methods. As you can see from the code, the obvious difference is that fromCharCode is a static method of string, and charCodeAt is the method of the string (hanging above the String.prototype). Then the opposite is the effect of the two, and the following is the explanation given by http://www.w3school.com.cn:
fromCharCode () can accept a specified Unicode value, and then return a string.
The charCodeAt () method returns the Unicode encoding of the character at the specified position. This return value is an integer between 0-65535.
Specifically to SUCC, take the string ' Hello Xesam ' For example, get all the characters ' Hello Xesa ' except the end character, then add a character ' n ' after ' m ' in the Unicode table, so the result is ' Hello Xesan '
On this basis, we want to print all the letters from ' a ' to ' Z ', and we can use the following functions:
Copy Code code 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 ');

Copy Code code as follows:

Function times (count) {
Return count < 1? ': New Array (count + 1). Join (this);
}

The Times function is to repeat the entire string, whose main idea is to invoke the current character as the connector for the array to get the expected result. Of course, it can be added by circulation, but not so concise.
If you want to repeat each character within a string, you can use the same idea:
Copy Code code as follows:

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 These four are mainly about variable name conversions.
Camelize: Converts a horizontal line-delimited string to a Camel form
Capitalize: Converts the first letter of a string to uppercase and all other letters to lowercase.
Underscore: Converts a string of Camel forms into a series of words separated by an underscore ("_").
Dasherize: Replace the underline in the string with the horizontal line ("_" replaced with "-").
Most obviously, you can use "class and float do not belong to this category" in the conversion of CSS properties to the style property of the DOM. For the above method, the CSS property can be converted to the corresponding Dom's style property using the Camelize method, but this method is not in turn, so the underscore-> dasherize method must be called continuously.
Copy Code code as follows:

function Camelize () {
Return This.replace (/-+ (.)? /g, function (match, CHR) {
Return CHR? Chr.touppercase (): ';
});
}

The core is the use of the Replace method, the other is quite simple, see "Analysis of the string of replace method application"

Copy Code code as follows:

Function capitalize () {
Return This.charat (0). toUpperCase () + this.substring (1). toLowerCase ();
}

Note here that the CharAt (CharAt () method returns the characters at the specified position. And charcodeat the difference is OK.

Copy Code code 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 illustrate the steps:
Copy Code code as follows:

' 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 only suits the camel form, is must have ' the peak '.
Copy Code code as follows:

function Dasherize () {
Return This.replace (/_/g, '-');
}

This is just a simple character replacement.
From Little Western Hills.

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.