ホームページ  >  記事  >  ウェブフロントエンド  >  プロトタイプ文字列オブジェクト learning_prototype

プロトタイプ文字列オブジェクト learning_prototype

WBOY
WBOYオリジナル
2016-05-16 18:49:481251ブラウズ

コードをコピー コードは次のとおりです:

//String オブジェクトの静的メソッド
Object.extend(String, {
interpret: function(value) {
return value == null ? '' : String(value);
},
specialChar: {
'b': '\b',
't': '\t',
'n': '\n',
'f': '\f',
'r': '\r',
'\': '\\'
}
}); extend(String.prototype, (function() {

//内部メソッド、gsub 関数と sub 関数の置換パラメータを初期化します。
function prepareReplacement(replacement) {
if (Object.isFunction(replacement) ) return replace;
var template = new Template(replacement);
return function(match) { return template.evaluate(match) };

// すべてを置換で置き換えますパターンに一致する文字列
//置換が関数ではない場合、パラメータのパターンが Template.pattern になる再帰呼び出しが行われることに注意してください
//Template の評価メソッドを参照できますここの構造は非常に巧妙で、while ループの else 部分がこの再帰呼び出しの結果を処理します。
function gsub(pattern, replace) {
var result = '', source = this, match; 🎜>replacement = prepareReplacement(replacement );

if (Object.isString(pattern))
pattern = RegExp.escape(pattern); // パターンパラメータが null の場合または ''、文字全体を使用します。 文字列は 1 文字で分割され、各文字の前後に置換が追加されます。
if (!(pattern.length || pattern.source)) {
replacement = replace ('');
return 置換source .split('').join(replacement) replace;

while (source.length > 0) {
//Ifソースがパターンに一致する
if (match = source .match(pattern)) {
replacement(match)); // 一致する文字の後の部分を次の一致のソースに割り当てます
source = source.slice(match.index match[0].length);
} else { //ソースがパターンと一致しない場合は、ソースを結果に直接追加し、ソースを空のままにし、ループを終了します
result =source,source = '';
}

}
return result;
}

// 基本的な意味は gsub と同じです。
function sub(pattern, replacement, count) {
replacement = prepareReplacement(replacement);
count = Object.isUnknown(count); を示す追加の count パラメータがあることを示します。 : count;

return this.gsub(pattern, function(match) {
if (--count return replace(match);
});
}

//パターンに一致する文字列のイテレータを呼び出します
function scan(pattern, iterator) {
this.gsub(pattern, iterator); return String(this);

//指定された長さに応じて文字列を切り詰めます
function truncate(length, truncation) {
length = length
; truncation = Object.isUnknown(truncation) ? '...' : truncation;
return this.length > length ?
this.slice(0, length - truncation.length) truncation : String(this);
}

//文字列の前後のスペースを削除します。
functionstrip() {
return this.replace(/^s /, '').replace(/s $/ , '');
}

//文字列の HTML タグを削除します
functionstripTags() {
return this.replace(/]) )?>|/ gi, '');
}

//削除文字列からのスクリプト タグ
functionstripScripts() {
return this.replace(new RegExp(Prototype.ScriptFragment, ' img'), '');

//文字列内のスクリプトの内容を取得します。
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];
});
}

//文字列内のスクリプトの内容を実行します
function evalScripts () {
return this.extractScripts().map(function(script) { return eval(script) });
}

//「>&」などの HTML コンテンツを標準の HTML 式に置き換えます。
escapeHTML.text.data = this;
returnscapeHTML.div.innerHTML;

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

// 文字列をクエリパラメータに分割します区切りパラメータに応じた形式
function toQueryParams(separator) {
var match = this.strip().match( /([^?#]*)(#.*)?$/); >if (!match) return { };

return match[1].split(separator || '& ').inject({ }、 function(hash, ペア) {
if ((pair = parit.split('='))[0]) {
var key = decodeURIComponent(pair.shift()); = ペア.長さ > 1 ? ペア.ジョイン('=') : ペア
if (値 != 未定義) 値 =

if (ハッシュ内のキー) ) {
if (!Object.isArray(hash[key])) ハッシュ[キー] = [ハッシュ[キー]]
ハッシュ[キー].push(値); else ハッシュ[キー] = 値;
}
ハッシュを返す;
}

関数 toArray() {
return this.split('') ;
}

//文字列の文字を返します
function succ() {
return this.slice(0, this.length - 1)
String.fromCharCode( this .charCodeAt(this.length - 1) 1);
}

//繰り返しの文字列を取得します
function time(count) {
return count < Array(count 1).join(this);
}

//CSS スタイルの文字列をスクリプト形式に変換します
function Camelize() {
var Parts = this .split('- '), len = Parts.length;
if (len == 1) return Parts[0];

var Camelized = this.charAt(0) == '-'
? [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
}

//大文字にする最初の文字
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-zd])([A-Z])/,'#{1} _#{2 }').gsub(/-/,'_').toLowerCase();
}

//'border_bottom_width'.dasherize();
// 'border- bottom-width'
function dumperize() {
return this.gsub(/_/,'-')
}

//文字列のデバッグ指向のバージョンを返します。 (デバッグに使用される文字列を返します)
function Inspection(useDoubleQuotes) {
varscapeString = this.gsub(/[x00-x1f\]/, function(match) {
varcharacter = String.specialChar [match[0]]; 戻り文字 ? : '\u00' match[0].charCodeAt().toPaddedString(2, 16);
if (useDoubleQuotes) "' エスケープ文字列.replace(/"/g, '\"') '"';
return "'" エスケープ文字列.replace(/'/g, '\"') "'" ; 🎜>
function toJSON() {
return this.inspect(true);
}

function unfilterJSON(filter) {
return this.sub (filter || プロトタイプ。 JSONFilter, '#{1}');
}

関数 isJSON() {
var str = this;
if (str.blank()) return false; str = this.replace(/\./g, '@').replace(/"[^"\nr]*"/g, '');
return (/^[ ,:{}[] 0-9.- Eaeflnr-u nrt]*$​​/).test(str);
}

//このセキュリティ メソッドは内部的に呼び出されます。 🎜>function evalJSON(sanitize) {
var json = this.unfilterJSON();
try {
if (!sanitize || json.isJSON()) return eval(' (' json ')' );
} catch (e) { }
throw new SyntaxError('不正な形式の JSON 文字列: ' this.inspect());
}

function include(pattern) {
return this.indexOf(pattern) > -1;

function startingWith(pattern) {
return this.indexOf(pattern) === 0 ; 🎜>
関数 endWith(パターン) {
var d = this.length - pattern.length;
return d >= 0 && this.lastIndexOf(pattern) === d;

関数 empty() {
return this == '';

functionblank() {
return /^s* $/.test(this );
}

//Template の評価メソッドと同じ
function interpolate(object, pattern) {
return new Template(this, pattern).evaluate (object); }

return {
gsub: gsub、
sub: sub、
scan: スキャン、
truncate: 切り捨て、
strip: String .prototype.trim ? prototype.trim:strip、
stripTags:stripTags、
stripScripts:stripScripts、
extractScripts:extractScripts、
evalScripts:evalScripts、
escapeHTML:escapeHTML、
unescapeHTML:unescapeHTML、
toQueryParams: toQueryParams、
parseQuery: toQueryParams、
toArray: toArray、
succ: succ、
times: 回、
camelize: Camelize、
Capitalize: Capitalize、
アンダースコア: アンダースコア、
dasherize: ダッシャライズ、
inspect: 検査、
toJSON: toJSON、
unfilterJSON: unfilterJSON、
isJSON: isJSON、
evalJSON : evalJSON、
include : include、
startsWith:startsWith、
endsWith:endsWith、
empty:空、
blank:空白、
interpolate:補間
})()); ;

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

String.prototype.escapeHTML.div.appendChild(String.prototype.escapeHTML.text);
//以下はブラウザの互換性の問題を解決すると推定されます
if ( '' .escapeHTML() !== '') {
String.prototype.escapeHTML = function() {
return this.replace(/&/g,'&' ).replace(/< ;/g,'<').replace(/>/g,'>');
};

if (''.unescapeHTML() !== '') {
String.prototype.unescapeHTML = function() {
return this.stripTags( ).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
Only examples of some important methods are given below, simple methods are skipped

escapeHTML() /unescapeHTML():

Copy code The code is as follows:

'
This is an article
'.escapeHTML();
// -> "
This is an article
'x > 10'.unescapeHTML()
// -> 'x > 10' '

Pride & Prejudice

'.unescapeHTML()
// -> '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 it. The concept of XSS is given below:

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 by other users.

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

'lorem... '.evalScripts();
// -> [4]

''.evalScripts();
// -> [4, undefined] (and displays 'hello world!' in the alert dialog )

gsub() /sub():
Copy code The 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 ''   match[1]   ''; });
// -> 'a pear an orange'

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

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 ''   match[1]   ''; });
// -> 'a pear ![an orange](/img/orange.jpg)'

markdown.sub(/![(.*?)]((.*?))/, '#{1}');
// -> 'a pear ![an orange](/img/orange.jpg)'

interpolate() :
复制代码 代码如下:

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

scan() :
复制代码 代码如下:

var fruits = [];
'apple, pear & orange'.scan(/w /, function(match){ fruits.push(match[0])}); fruits.inspect()
// -> ['apple', 'pear', 'orange']

times() :
复制代码 代码如下:

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

toQueryParams():
复制代码 代码如下:

'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 on rails'.toQueryParams();
// -> {tag: 'ruby on rails'}

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

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。