Prototype String object Learning

Source: Internet
Author: User
Tags tojson ruby on rails

Copy codeThe Code is as follows:
// Static method of String object
Object. extend (String ,{
Interpret: function (value ){
Return value = null? '': String (value );
},
SpecialChar :{
'\ B': '\ B ',
'\ T':' \ t ',
'\ N':' \ n ',
'\ F':' \ F ',
'\ R':' \ R ',
'\\':'\\\\'
}
});

Object. extend (String. prototype, (function (){

// Internal method, which initializes the replacement parameter for the gsub and sub Functions
Function prepareReplacement (replacement ){
If (Object. isFunction (replacement) return replacement;
Var template = new Template (replacement );
Return function (match) {return template. evaluate (match )};
}

// Replacement is used to replace all pattern-compliant strings.
// Note that when replacement is not a function, there will be a recursive call, where the parameter pattern will change to Template. pattern
// You can refer to the evaluate Method of the Template. The structure here is very clever. The else part of the while loop will process the result of this recursive call.
Function gsub (pattern, replacement ){
Var result = '', source = this, match;
Replacement = prepareReplacement (replacement );

If (Object. isString (pattern ))
Pattern = RegExp. escape (pattern );

// If the pattern parameter is null or '', separate the entire string by a single character and add replacement before and after each character.
If (! (Pattern. length | pattern. source )){
Replacement = replacement ('');
Return replacement + source. split (''). join (replacement) + replacement;
}

While (source. length> 0 ){
// If source matches pattern
If (match = source. match (pattern )){
// Retrieve the matching string
Result + = source. slice (0, match. index );
// Match and replace
Result + = String. interpret (replacement (match ));
// Assign the part after matching characters to source for the next matching
Source = source. slice (match. index + match [0]. length );
} Else {// If the source does not match the pattern, add the source directly to the result and leave the source empty to end the loop.
Result + = source, source = '';
}

}
Return result;
}

// The basic meaning is the same as that of gsub, except that one more count parameter indicates the number of times to be replaced.
Function sub (pattern, replacement, count ){
Replacement = prepareReplacement (replacement );
Count = Object. isUndefined (count )? 1: count;

Return this. gsub (pattern, function (match ){
If (-- count <0) return match [0];
Return replacement (match );
});
}

// Call the iterator that matches the pattern string
Function scan (pattern, iterator ){
This. gsub (pattern, iterator );
Return String (this );
}

// Truncate the string based on the given length
Function truncate (length, truncation ){
Length = length | 30;
Truncation = Object. isUndefined (truncation )? '...': Truncation;
Return this. length> length?
This. slice (0, length-truncation. length) + truncation: String (this );
}

// Remove spaces before and after the string
Function strip (){
Return this. replace (/^ \ s +/, ''). replace (/\ s + $ /,'');
}

// Remove the html mark of the string
Function stripTags (){
Return this. replace (/<\ w + (\ s + ("[^"] * "| '[^'] * '| [^>]) +)?> | <\/\ W +>/gi ,'');
}

// Remove the script mark from the string
Function stripScripts (){
Return this. replace (new RegExp (Prototype. ScriptFragment, 'img '),'');
}

// Obtain the script content in the string
Function extractScripts (){
Var matchAll = new RegExp (Prototype. ScriptFragment, 'img ');
Var matchOne = new RegExp (Prototype. ScriptFragment, 'im ');
Return (this. match (matchAll) | []). map (function (scriptTag ){
Return (scriptTag. match (matchOne) | ['','']) [1];
});
}

// Execute the script content in the string
Function evalScripts (){
Return this. extractScripts (). map (function (script) {return eval (script )});
}

// Escape HTML content. For example, replace '<> &' and other special characters with standard HTML expressions.
Function escapeHTML (){
EscapeHTML. text. data = this;
Return escapeHTML. div. innerHTML;
}

Function unescapeHTML (){
Var div = document. createElement ('div ');
Div. innerHTML = this. stripTags ();
Return div. childNodes [0]? (Div. childNodes. length> 1?
$ A (div. childNodes). inject ('', function (memo, node) {return memo + node. nodeValue }):
Div. childNodes [0]. nodeValue ):'';
}

// Splits the string into query parameters according to the separator Parameter
Function toQueryParams (separator ){
Var match = this. strip (). match (/([^? #] *) (#. *)? $ /);
If (! Match) return {};

Return match [1]. split (separator | '&'). inject ({}, function (hash, pair ){
If (pair = pair. split ('=') [0]) {
Var key = decodeURIComponent (pair. shift ());
Var value = pair. length> 1? Pair. join ('='): pair [0];
If (value! = Undefined) value = decodeURIComponent (value );

If (key in hash ){
If (! Object. isArray (hash [key]) hash [key] = [hash [key];
Hash [key]. push (value );
}
Else hash [key] = value;
}
Return hash;
});
}

Function toArray (){
Return this. split ('');
}

// Returns string characters
Function succ (){
Return this. slice (0, this. length-1) +
String. fromCharCode (this. charCodeAt (this. length-1) + 1 );
}

// Obtain duplicate strings
Function times (count ){
Return count <1? '': New Array (count + 1). join (this );
}

// Converts a css style string to a script.
Function camelize (){
Var parts = this. split ('-'), len = parts. length;
If (len = 1) return parts [0];

Var camelized = this. charAt (0) = '-'
? Parts [0]. charAt (0). toUpperCase () + parts [0]. substring (1)
: Parts [0];

For (var I = 1; I <len; I ++)
Camreceived + = parts [I]. charAt (0). toUpperCase () + parts [I]. substring (1 );

Return camreceived;
}

// Uppercase letters
Function capitalize (){
Return this. charAt (0). toUpperCase () + this. substring (1). toLowerCase ();
}

// 'Borderbottomwidth '. underscore ();
//-> 'Border _ bottom_width'
Function underscore (){
Return this. gsub (/::/,'/'). gsub (/([A-Z] +) ([A-Z] [a-z])/, '# {1} _ #{2 }'). gsub (/([a-z \ d]) ([A-Z])/, '# {1} _ #{2 }'). gsub (/-/,'_'). toLowerCase ();
}

// 'Border _ bottom_width '. dasherize ();
//-> 'Border-bottom-width'
Function dasherize (){
Return this. gsub (/_/,'-');
}

// Returns a debug-oriented version of the string (Returns a string used for tuning)
Function inspect (useDoubleQuotes ){
Var escapedString = this. gsub (/[\ x00-\ x1f \]/, function (match ){
Var character = String. specialChar [match [0];
Return character? Character: '\ u00' + match [0]. charCodeAt (). toPaddedString (2, 16 );
});
If (useDoubleQuotes) return '"' + escapedString. replace (/"/g, '\ "') + '"';
Return "'" + escapedString. replace (/'/g, '\ '') + "'";
}

Function toJSON (){
Return this. inspect (true );
}

Function unfilterJSON (filter ){
Return this. sub (filter | Prototype. JSONFilter, '# {1 }');
}

Function isJSON (){
Var str = this;
If (str. blank () return false;
Str = this. replace (/\\. /g ,'@'). replace (/"[^" \ n \ r] * "/g ,'');
Return (/^ [, :{}\ [\] 0-9. \-+ Eaeflnr-u \ n \ r \ t] * $/). test (str );
}

// Strips comment delimiters around Ajax JSON or JavaScript responses. This security method is called internally.
Function evalJSON (sanitize ){
Var json = this. unfilterJSON ();
Try {
If (! Sanitize | json. isJSON () return eval ('+ json + ')');
} Catch (e ){}
Throw new SyntaxError ('badly formed JSON string: '+ this. inspect ());
}

Function include (pattern ){
Return this. indexOf (pattern)>-1;
}

Function startsWith (pattern ){
Return this. indexOf (pattern) = 0;
}

Function endsWith (pattern ){
Var d = this. length-pattern. length;
Return d> = 0 & this. lastIndexOf (pattern) = d;
}

Function empty (){
Return this = '';
}

Function blank (){
Return/^ \ s * $/. test (this );
}

// Same as the evaluate Method of Template
Function interpolate (object, pattern ){
Return new Template (this, pattern). evaluate (object );
}

Return {
Gsub: gsub,
Sub: sub,
Scan: scan,
Truncate: truncate,
Strip: String. prototype. trim? String. prototype. trim: strip,
StripTags: stripTags,
StripScripts: stripScripts,
ExtractScripts: extractScripts,
EvalScripts: evalScripts,
EscapeHTML: escapeHTML,
UnescapeHTML: unescapeHTML,
ToQueryParams: toQueryParams,
ParseQuery: toQueryParams,
ToArray: toArray,
Succ: succ,
Times: times,
Camelize: camelize,
Capitalize: capitalize,
Underscore: underscore,
Dasherize: dasherize,
Inspect: inspect,
ToJSON: toJSON,
UnfilterJSON: unfilterJSON,
IsJSON: isJSON,
EvalJSON: evalJSON,
Include: include,
StartsWith: startsWith,
EndsWith: endsWith,
Empty: empty,
Blank: blank,
Interpolate: interpolate
};
})());

Object. extend (String. prototype. escapeHTML ,{
Div: document. createElement ('div '),
Text: document. createTextNode ('')
});

String. prototype. escapeHTML. div. appendChild (String. prototype. escapeHTML. text );
// The following estimation solves the problem of browser compatibility.
If ('<\ n>'. escapeHTML ()! = '<\ N> '){
String. prototype. escapeHTML = function (){
Return this. replace (/&/g, '&'). replace (/</g, '<'). replace (/>/g, '> ');
};
}

If ('<\ n>'. unescapeHTML ()! = '<\ N> '){
String. prototype. unescapeHTML = function (){
Return this. stripTags (). replace (/</g, '<'). replace (/>/g, '> '). replace (// g ,'&');
};
}

Blank
Camelize
Capitalize
Dasherize
Empty
EndsWith
EscapeHTML
EvalJSON
EvalScripts
ExtractScripts
Gsub
Include
Inspect
Interpolate
IsJSON
ParseQuery
Scan
StartsWith
Strip
StripScripts
StripTags
Sub
Succ
Times
ToArray
ToJSON
ToQueryParams
Truncate
Underscore
UnescapeHTML
UnfilterJSON
The following is an example of some important methods. The simple method is omitted.

EscapeHTML ()/unescapeHTML ():
Copy codeThe Code is as follows:
'<Div class = "article"> This is an article </div>'. escapeHTML ();
//-> "<Div class =" article "> This is an article </div>"

'X> 10'. unescapeHTML ()
//-> 'X> 10''' //-> 'Pride & Prejudice'

EvalJSON()/EvalScripts():

There are several methods in the String object to prevent XSS Attack attacks. If you are interested, you can search for them. The following describes the concept of XSS:

Cross-site scripting (XSS) is a typeComputer security VulnerabilityTypically found inWeb applicationsWhich allowCode injectionBy malicious web users intoWeb pagesViewed by other users.
Copy codeThe Code is as follows:
Var person = '{"name": "Violet", "occupation": "character"}'. evalJSON ();
Person. name;
//-> "Violet"

Person = 'maid () '. evalJSON (true );
//-> SyntaxError: Badly formed JSON string: 'grabuserpassword ()'

Person = '/*-secure-\ n {"name": "Violet", "occupation": "character"} \ n */'. evalJSON ()
Person. name;
//-> "Violet"

Copy codeThe Code is as follows:
'Lorem... <script type = "text/javascript"> <! --
2 + 2
// --> </Script> '. evalScripts ();
//-> [4]

'<Script type = "text/javascript"> <! --
2 + 2
// --> </Script> <script type = "text/javascript"> <! --
Alert ("hello world! ")
// --> </Script> '. evalScripts ();
//-> [4, undefined] (and displays 'Hello world! 'In the alert dialog)

Gsub ()/sub ():
Copy codeThe Code is as follows:
Var mouseEvents = 'click dblclick mousedown mouseup mouseover mousemove mouseout'; mouseEvents. gsub ('',',');
//-> 'Click, dblclick, mousedown, mouseup, mouseover, mousemove, mouseout'

MouseEvents. gsub (/\ w +/, function (match) {return 'on' + match [0]. capitalize ()});
//-> 'Onclick onDblclick onMousedown onMouseup onMouseover onMousemove onmouseout'

Var markdown = '! [A pear] (/img/pear.jpg )! [An orange] (/img/orange.jpg )';
Markdown. gsub (/! \[(.*?) \] \ (. *?) \)/, Function (match) {return ' ';});
//-> ' '

// ================================================ ================

Var fruits = 'apple pear orange ';
Fruits. sub ('', ','); //-> 'apple, pear orange'
Fruits. sub ('', ',', 1); //-> 'apple, pear orange'
Fruits. sub ('', ',', 2); //-> 'apple, pear, orange'
Fruits. sub (/\ w +/, function (match) {return match [0]. capitalize () + ','}, 2 );
//-> 'Apple, Pear, orange'

Var markdown = '! [A pear] (/img/pear.jpg )! [An orange] (/img/orange.jpg )';
Markdown. sub (/! \[(.*?) \] \ (. *?) \)/, Function (match) {return ' ';});
//-> '! [An orange] (/img/orange.jpg )'

Markdown. sub (/! \[(.*?) \] \ (. *?) \)/, ' ');
//-> '! [An orange] (/img/orange.jpg )'

Interpolate ():
Copy codeThe Code is as follows:
"# {Animals} on a # {transport}". interpolate ({animals: "Pigs", transport: "Surfboard "});
//-> "Pigs on a Surfboard"

Scan ():
Copy codeThe Code is as follows:
Var fruits = [];
'Apple, pear & orange '. scan (/\ w +/, function (match) {fruits. push (match [0])}); fruits. inspect ()
//-> ['Apple', 'pear ', 'Orange']

Times ():
Copy codeThe Code is as follows:
"Echo". times (3); //-> "echo"

ToQueryParams ():
Copy codeThe Code is as follows:
'Section = blog & id = 45'. toQueryParams ();
//-> {Section: 'blog ', id: '45 '}

'Section = blog; id = 45'. toQueryParams ();
//-> {Section: 'blog ', id: '45 '}

'Http: // www.example.com? Section = blog & id = 45 # comments '. toQueryParams ();
//-> {Section: 'blog ', id: '45 '}

'Section = blog & tag = javascript & tag = prototype & tag = doc'. toQueryParams ();
//-> {Section: 'blog ', tag: ['javascript', 'prototype', 'Doc']}

'Tag = ruby % 20on % 20rails '. toQueryParams ();
//-> {Tag: 'Ruby on rails '}

'Id = 45 & raw'. toQueryParams ();
//-> {Id: '45', raw: undefined}

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.