프로토타입 문자열 객체 학습_프로토타입

WBOY
풀어 주다: 2016-05-16 18:49:48
원래의
1265명이 탐색했습니다.

코드 복사 코드는 다음과 같습니다.

//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 및 하위 함수에 대한 대체 매개변수 초기화
function prepareReplacement(replacement) {
if (Object.isFunction(replacement) ) return replacement;
var template = new Template(replacement);
return function(match) { return template.evaluate(match) }

//모두 교체로 바꾸기 패턴
과 일치하는 문자열//대체가 함수가 아닌 경우 매개변수 패턴이 Template.pattern이 되는 재귀 호출이 있습니다.
//Template의 평가 메소드를 참조할 수 있습니다. . 여기 구조는 매우 영리합니다. while 루프의 else 부분은 이 재귀 호출의 결과를 처리합니다.
function gsub(pattern, replacement) {
var result = '', source = this, match; 🎜>replacement = prepareReplacement(replacement );

if (Object.isString(pattern))
pattern = RegExp.escape(pattern);

//패턴 매개변수가 null인 경우 또는 '', 전체 문자 사용 문자열은 단일 문자로 분할되고 각 문자 앞뒤에 대체가 추가됩니다.
if (!(pattern.length || Pattern.source)) {
replacement = replacement ('');
교체 반환 source .split('').join(replacement) replacement
}

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와 동일합니다. 교체 횟수를 나타내는 추가 count 매개변수가 있음
function sub(pattern, replacement, count) {
replacement = prepareReplacement(replacement)
count = Object.isUndefine(count) ? : count;

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

//패턴과 일치하는 문자열에 대해 반복자 호출
function scan(pattern, iterator) {
this.gsub(pattern, iterator); >return String(this);

//주어진 길이에 따라 문자열을 자릅니다.
function truncate(length, truncation) {
length = length
truncation = Object.isUndefine(truncation) ? '...' : truncation;
return this.length > length ?
this.slice(0, length - truncation.length) truncation: 문자열(this) ;
}

//문자열 앞뒤 공백 제거
function Strip() {
return this.replace(/^s /, '').replace(/s $ /, '');

//문자열의 html 태그 제거
function StripTags() {
return this.replace(/]) )?>|/ gi, '')
}

// 문자열에서 스크립트 태그를 제거합니다.
function StripScripts() {
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 표현식으로 대체합니다.
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) : '';
}

//문자열을 쿼리로 분할 구분 기호 매개 변수에 따른 매개 변수 형식
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 = decodeURIComponent(value); ) {
if (!Object.isArray(hash[key])) hash[key] = [hash[key]]
hash[key].push(value)
}
else hash[key] = value;
}
return hash;
})
}

function toArray() {
return this.split('') ;
}

//문자열의 문자를 반환합니다.
function succ() {
return this.slice(0, this.length - 1)
String.fromCharCode( this .charCodeAt(this.length - 1) 1);
}

//반복되는 문자열 가져오기
function times(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 camelized;

//Capitalize 첫 글자
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()
// -> ; Bottom-width'
function dasherize() {
return this.gsub(/_/,'-')
}

//디버그 지향 버전의 문자열을 반환합니다. (디버깅에 사용되는 문자열을 반환)
functionspec(useDoubleQuotes) {
var escapedString = this.gsub(/[x00-x1f\]/, function(match) {
var Character = String.specialChar [match[0]];
문자 ? 문자 반환: '\u00' match[0].charCodeAt().toPendedString(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(/"[^"\nr]*"/g, '');
return (/^[ ,:{}[] 0-9.- Eaeflnr-u nrt]*$/).test(str);
}

//Ajax JSON 또는 JavaScript 응답 주위의 주석 구분 기호를 제거합니다. 🎜>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) >
}

function startWith(pattern) {
return this.indexOf(pattern) === 0
}

function endWith(pattern) {
var d = this.length - Pattern.length
return d >= 0 && this.lastIndexOf(pattern) === d;

function 공백() {
return this == ''
}

function 공백() {
return /^s* $/.test(this );
}

//템플릿의 평가 메소드와 동일
function interpolate(object, Pattern) {
return new Template(this, Pattern).evaluate (object); }

return {
gsub: gsub,
sub: sub,
scan: scan,
truncate: truncate,
strip: 문자열 .prototype.trim ? 프로토타입.trim : 스트립,
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,
밑줄: 밑줄,
dasherize: dasherize,
inspect: 검사,
toJSON: toJSON,
unfilterJSON: unfilterJSON,
isJSON: isJSON,
evalJSON: evalJSON,
include : include,
startsWith: startWith,
endsWith: endWith,
empty: 비어 있음,
blank: 공백,
보간: 보간
})()) ;

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,'&');
}

空白
キャメル化
大文字化
ダッシュ化

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
いくつかの重要なメソッドの例のみを以下に示します。単純なメソッドはスキップします
escapeHTML() /unescapeHTML():


コードをコピー コードは次のとおりです:
'
これは記事です
'.escapeHTML();
// -> "
これは記事です< ;/div> ;"

'x > 10'.unescapeHTML()
// -> 'x > 10' '

高慢と偏見

'.unescapeHTML ()
// -> 「高慢と偏見」


evalJSON() /evalScripts() :

XSS 攻撃攻撃を防ぐためのメソッドが String オブジェクトにいくつかあります。興味がある場合は、XSS の概念を以下に示します。 >

クロスサイト スクリプティング (XSS) は、 で通常見られる コンピューター セキュリティ 脆弱性 の一種です。悪意のある Web ユーザーによる、他のユーザーが閲覧する Web ページへの コード インジェクションを許可する Web アプリケーション。 🎜>
コードをコピーします

person = 'grabUserPassword() '.evalJSON (true);
//-> 構文エラー: JSON 文字列の形式が正しくありません: 'grabUserPassword()'

person = '/*-secure-n{"name": "Violet" , "職業 ": "キャラクター"}n*/'.evalJSON()
person.name
//-> "バイオレット"






コードをコピー

コードは次のとおりです:'lorem... '.evalScripts(); // -> [4]
''.evalScripts();
// -> (および 'hello world' が表示されます) !' アラートダイアログ内 )


gsub() /sub():



コードをコピー

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

var MouseEvents = 'クリック dblclick マウスダウン マウスアップ マウスオーバー マウス移動 マウスアウト';マウスイベント.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 = '![梨](/img/pear.jpg) ![オレンジ](/img/orange.jpg)';
markdown.gsub(/![(.*?)]((.*?))/, function(match){ return '' match[1] ''; });
// -> '梨 オレンジ'

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

var フルーツ = 'リンゴ、梨、オレンジ';
fruits.sub(' ', ', '); // -> 'リンゴ、梨、オレンジ'
fruits.sub(' ', ', ', 1); // -> 'リンゴ、梨、オレンジ'
fruits.sub(' ', ', ', 2); // -> 'リンゴ、梨、オレンジ'
fruits.sub(/w /, function(match){return match[0].capitalize() ','}, 2);
// -> 'リンゴ、梨、オレンジ'

var markdown = '![梨](/img/pear.jpg) ![オレンジ](/img/orange.jpg)';
markdown.sub(/![(.*?)]((.*?))/, function(match){ return '' match[1] ''; });
// -> '梨 ![オレンジ](/img/orange.jpg)'

markdown.sub(/![(.*?)]((.*?))/, '# {1}');
// -> '梨 ![オレンジ](/img/orange.jpg)'

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

"#{動物} on a #{transport}".interpolate({ 動物: "豚", 輸送: "サーフボード" }) ;
//-> 「サーフボードに乗った豚」

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

var Fruits = [];
'リンゴ、梨、オレンジ'.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();
// -> {セクション: 'ブログ', id: '45'}

'section=blog;id=45'.toQueryParams();
// -> {セクション: 'ブログ', id: '45'}

'http://www.example.com?section=blog&id=45#comments'.toQueryParams();
// -> {セクション: 'ブログ', ID: '45'}

'section=blog&tag=javascript&tag=prototype&tag=doc'.toQueryParams();
// -> {セクション: 'ブログ', タグ:['javascript', 'プロトタイプ', 'ドキュメント']}

'tag=ruby on Rails'.toQueryParams();
// -> {tag: 'ruby on Rails'}

'id=45&raw'.toQueryParams();
// -> {id: '45'、生: 未定義}

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!