Prototype String Object Learning _prototype

Source: Internet
Author: User
Tags eval extend html tags json pear tojson trim ruby on rails

Copy Code code 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 methods, initialization of replacement parameters for 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)};
}

Replace all pattern strings with replacement
Note that when replacement is not a function, there is a recursive call in which the parameter pattern changes to Template.pattern
You can refer to the Evaluate method of template, which is very ingenious, where the else part of the while loop handles 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)) {
Remove the string before the match
Result + = Source.slice (0, Match.Index);
Match replacement
result = String.interpret (match) (replacement);
Assigns the part after the matching character to source for the next match
Source = Source.slice (Match.Index + match[0].length);
else {//if source does not match pattern, add source directly to the result and leave the source blank to end the loop
result = = Source, Source = ';
}

}
return result;
}

The basic meaning is the same as gsub, just one more count parameter, which means to replace several
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);
});
}

Iterator calls to strings that match pattern
function scan (pattern, iterator) {
This.gsub (pattern, iterator);
Return String (this);
}

Truncates a string at a 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 the space before and after the string
function strip () {
Return This.replace (/^\s+/, '). Replace (/\s+$/, ");
}

Remove HTML tags from strings
function Striptags () {
Return This.replace (/<\w+ \s+ ("[^"]* "|") [^']*'| [^>]) +)? >|<\/\w+>/gi, "");
}

Remove the script tag from the string
function stripscripts () {
Return This.replace (New RegExp (prototype.scriptfragment, ' img '), "");
}

Get the script content in a 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)});
}

Escaping HTML content, such as replacing special characters such as ' <>& ' into standard HTML representations
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): ';
}

Split 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 the character of a string
function succ () {
Return This.slice (0, this.length-1) +
String.fromCharCode (This.charcodeat (this.length-1) + 1);
}

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

Converts a string of CSS style types into a scripted form
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++)
Camelized + + parts[i].charat (0). toUpperCase () + parts[i].substring (1);

return camelized;
}

Capitalize first letter
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 the modal)
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 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 template's Evaluate method.
function Interpolate (object, pattern) {
Return to 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 estimate addresses browser compatibility issues
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
Here are only a few examples of important methods, the simple method is skipped

Escapehtml ()/unescapehtml ():

Copy Code code as follows:

' <div class= ' article ' >this is a article</div> '. escapehtml ();
-> "<div class=" article ">this is a article</div>"

' x > A '. unescapehtml ()
-> ' x > -> ' Pride & Prejudice '

Evaljson()/evalscripts():

A few of the methods in the string object are designed to prevent XSS attack attacks, interested in searching, and the following is the concept of XSS:

cross-site Scripting (XSS) is a type of computer security Vulnerability typically found in web Applications which allow code injection by malicious Web users into the Web pages viewed B Y other users.

Copy Code code as follows:

var person = ' {' name ': ' Violet ', ' occupation ': ' character '} '. Evaljson ();
Person.name;
-> "Violet"

person = ' grabuserpassword () '. Evaljson (True);
-> syntaxerror:badly formed JSON string: ' Grabuserpassword () '

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

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

var mouseevents = ' Click DblClick mousedown mouseup mouseover MouseMove '; 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 '

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 Code code as follows:

' #{animals} on a #{transport} '. interpolate ({animals: "Pigs", Transport: "Surfboard"});
-> "Pigs on a surfboard"

Scan ():
Copy Code code as follows:

var fruits = [];
' Apple, pear & orange '. Scan (/\w+/, function (match) {Fruits.push (match[0))}; Fruits.inspect ()
-> [' Apple ', ' pear ', ' orange ']

Times ():
Copy Code code as follows:

"echo". times (3); -> "Echo Echo Echo"

toqueryparams ():
Copy Code code 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: ' Blogs ', tag:[' JavaScript ', ' prototype ', ' Doc '}

' Tag=ruby%20on%20rails '. Toqueryparams ();
-> {tag: ' Ruby on Rails '}

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

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.