彩世界开奖app官网-彩世界平台官方网址(彩票平台)
做最好的网站
来自 彩世界平台官方网址 2019-11-28 06:04 的文章
当前位置: 彩世界开奖app官网 > 彩世界平台官方网址 > 正文

Prototype源码浅析 String部分之补充_prototype_脚本之

替换interpolate|sub|scan|truncate | gsubinterpolate : 将字符串看作一个模板,并使用 object 的属性填充它。 sub : 将字符串中前指定个个与 pattern 指定的模式匹配的子串用 replacement 替换 scan : 遍历字符串中与参数 pattern 指定的模式匹配的所有子串。返回原始字符串本身。 truncate : 将字符串截短为指定的长度, 并添加一个后缀。 gsub :将字符串中所有与 pattern 指定的模式匹配的值全部用 replacement 替换掉 上面的方法中,最重要的一个方法是gsub,具体说明参见《浅析Prototype的模板类--Template》 sub除了可以限定次数外,其他与gsub完全一致。 复制代码 代码如下: function sub(pattern, replacement, count) { replacement = prepareReplacement; count = Object.isUndefined ? 1 : count; return this.gsub(pattern, function { if return match[0]; return replacement; } scan也是一样的,不过scan最后返回的是字符串本身而已。 interpolate 是将字符串当做模板来用,核心还是gsub truncate 是唯一有点区别的。 以字符串'fuck the gfw'为例,truncate 的执行'fuck the gfw'.truncate的步骤是: 1、获得前面10 - '****'.length个字符 'fuck t' 2、拼上后缀'****',得到 'fuck t****',长度为10. 处理很简单,源码也简单: 复制代码 代码如下: function truncate { length = length || 30;//默认长度30 truncation = Object.isUndefined ? '...' : truncation;//默认后缀... return this.length > length ? this.slice(0, length - truncation.length) truncation : String; } 另:Prototype的一个方便之处就是随时可以抽取有用的代码作为单独的部分或者收为自己用。下面是单独提出来的模板方法。 复制代码 代码如下: function Template{ this.template = template; this.pattern = pattern || /})/; } Template.prototype = { function evaluate{ return gsub.call{ if{ return match[0] ''; } var before = match[1] || ''; if{ return match[2]; } var ctx = obj; var expr = match[3]; var pattern = /^([^.[] |[/; match = pattern.exec; if { return before; } while { var comp = match[1].search != -1 ? match[2].replace : match[1]; ctx = ctx[comp]; if (null == ctx || '' == match[3]) break; expr = expr.substring('[' == match[3] ? match[1].length : match[0].length); match = pattern.exec; } return before (ctx === null ? '' : String; } function gsub{ var pattern = this.pattern; var result = ''; var match = null; var source = this.template; if (!(pattern.length || pattern.source)) { replacement = replacement; return replacement source.split replacement; } while { if (match = source.match { result = source.slice; result = replacement === null ? '' : String; source = source.slice(match.index match[0].length); }else { result = source; source = ''; } } return result; } return { constructor : Template, evaluate : evaluate } })(); 复制代码 代码如下: var template = new Template('my age is : #{name.age}'); console.log(template.evaluate;//my age is : 24 String部分

This is an article

复制代码 代码如下://String对象的静态方法 Object.extend(String, { interpret: function { return value == null ? '' : String; }, specialChar: { 'b': '\b', 't': '\t', 'n': '\n', 'f': '\f', 'r': '\r', '\': '\\' } }); Object.extend(String.prototype, { //内部方法,为gsub和sub函数初始化replacement参数 function prepareReplacement { if (Object.isFunction return replacement; var template = new Template; return function { return template.evaluate }; } //用replacement替换所有符合pattern的字符串 //注意当replacement不为函数时,这里面会有一个递归调用,其中参数pattern会变为Template.pattern //可以参考Template的evaluate方法,这里构造的非常巧妙,在while循环里的else部分会处理这个递归调用的结果 function gsub { var result = '', source = this, match; replacement = prepareReplacement; if (Object.isString pattern = RegExp.escape; //如果pattern参数为null或者'',用把整个字符串按照单个字符分割,并且在每个字符的前后添加replacement if (!(pattern.length || pattern.source)) { replacement = replacement; return replacement source.split replacement; } while { //如果source匹配pattern if (match = source.match { //取出匹配之前的字符串 result = source.slice; //匹配替换 result = String.interpret; //把匹配字符之后的部分赋给source,进行下一次匹配 source = source.slice(match.index match[0].length); } else { //如果source不匹配pattern,则直接把source添加到结果上,并把source置空,结束循环 result = source, source = ''; } } return result; } //基本意思和gsub一样,只不过多一个count参数,表示要替换几次 function sub(pattern, replacement, count) { replacement = prepareReplacement; count = Object.isUndefined ? 1 : count; return this.gsub(pattern, function { if return match[0]; return replacement; } //对符合pattern的字符串进行iterator调用 function scan { this.gsub; return String; } //按照给定长度截断字符串 function truncate { length = length || 30; truncation = Object.isUndefined ? '...' : truncation; return this.length > length ? this.slice(0, length - truncation.length) truncation : String; } //剔除字符串前后空格 function strip() { return this.replace.replace; } //把字符串的html标记剔除 function stripTags() { return this.replace(/|/gi, ''); } //把字符串中的script标记剔除 function stripScripts() { return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), ''); } //获取字符串中的script内容 function extractScripts() { var matchAll = new RegExp(Prototype.ScriptFragment, 'img'); var matchOne = new RegExp(Prototype.ScriptFragment, 'im'); return || []).map { return (scriptTag.match || ['', ''])[1]; }); } //执行字符串中的script内容 function evalScripts() { return this.extractScripts().map { return eval; } //转义HTML内容,例如把'<>&'等特殊字符替换成标准的HTML表达形式 function escapeHTML() { escapeHTML.text.data = this; return escapeHTML.div.innerHTML; } function unescapeHTML() { var div = document.createElement; div.innerHTML = this.stripTags(); return div.childNodes[0] ? (div.childNodes.length > 1 ? $A.inject('', function { return memo node.nodeValue }) : div.childNodes[0].nodeValue) : ''; } //按照separator参数把字符串分割成查询参数形式 function toQueryParams { var match = this.strip return { }; return match[1].split.inject({ }, function { if ((pair = pair.split { var key = decodeURIComponent; var value = pair.length > 1 ? pair.join : pair[0]; if value = decodeURIComponent; if { if (!Object.isArray hash[key] = [hash[key]]; hash[key].push; } else hash[key] = value; } return hash; }); } function toArray() { return this.split; } //返回字符串的字符 function succ() { return this.slice String.fromCharCode(this.charCodeAt; } //获得重复的字符串 function times { return count < 1 ? '' : new Array; } //把css样式类型的字符串转换成脚本形式 function camelize() { var parts = this.split, len = parts.length; if return parts[0]; var camelized = this.charAt == '-' ? parts[0].charAt parts[0].substring : parts[0]; for (var i = 1; i < len; i ) camelized = parts[i].charAt parts[i].substring; return camelized; } //首字母大写 function capitalize() { return this.charAt this.substring; } //'borderBottomWidth'.underscore(); // -> 'border_bottom_width' function underscore() { return this.gsub.gsub/,'#{1}_); } //'border_bottom_width'.dasherize(); // -> 'border-bottom-width' function dasherize() { return this.gsub; } //Returns a debug-oriented version of the string function inspect { var escapedString = this.gsub(/[x00-x1f\]/, function { var character = String.specialChar[match[0]]; return character ? character : '\u00' match[0].charCodeAt().toPaddedString; if return '"' escapedString.replace '"'; return "'" escapedString.replace "'"; } function toJSON() { return this.inspect; } function unfilterJSON { return this.sub(filter || Prototype.JSONFilter, '#{1}'); } function isJSON() { var str = this; if return false; str = this.replace.replace; return (/^[,:{}[]0-9.- Eaeflnr-u nrt]*$/).test; } //Strips comment delimiters around Ajax JSON or JavaScript responses. This security method is called internally. function evalJSON { var json = this.unfilterJSON(); try { if (!sanitize || json.isJSON return eval; } catch { } throw new SyntaxError('Badly formed JSON string: ' this.inspect; } function include { return this.indexOf > -1; } function startsWith { return this.indexOf === 0; } function endsWith { var d = this.length - pattern.length; return d >= 0 && this.lastIndexOf === d; } function empty() { return this == ''; } function blank() { return /^s*$/.test; } //和Template的evaluate方法一样 function interpolate { return new Template.evaluate; } 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, text: document.createTextNode; String.prototype.escapeHTML.div.appendChild(String.prototype.escapeHTML.text); //以下估计是解决浏览器兼容问题 if !== '') { String.prototype.escapeHTML = function() { return this.replace.replace.replace; }; } if !== '') { String.prototype.unescapeHTML = function() { return this.stripTags.replace.replace; }; }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 下面只给出一些重要方法的例子,简单方法就略过了

escapeHTML :复制代码 代码如下:'

This is an article

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

'.escapeHTML(); // -> "

Pride & Prejudice

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

evalJSON :

String对象里面的有几个方法是为了防止XSS Attack攻击的,有兴趣的可以搜一下,下面给出XSS的概念:

Cross-site scripting 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. 复制代码 代码如下:var person = '{ "name": "Violet", "occupation": "character" }'.evalJSON(); person.name; //-> "Violet" person = 'grabUserPassword; //-> SyntaxError: Badly formed JSON string: 'grabUserPassword()' person = '/*-secure-n{"name": "Violet", "occupation": "character"}n*/'.evalJSON() person.name; //-> "Violet" 复制代码 代码如下:'lorem...

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

'.evalScripts(); // -> [4, undefined] (and displays 'hello world!' in the alert dialog)gsub :复制代码 代码如下:var mouseEvents = 'click dblclick mousedown mouseup mouseover mousemove mouseout'; mouseEvents.gsub; // -> 'click, dblclick, mousedown, mouseup, mouseover, mousemove, mouseout' mouseEvents.gsub(/w /, function{return 'on' match[0].capitalize; // -> 'onClick onDblclick onMousedown onMouseup onMouseover onMousemove onMouseout' var markdown = '![a pear] ![an orange]'; markdown.gsub/, function{ return '彩世界平台官方网址 1'; }); // -> '彩世界平台官方网址 2 彩世界平台官方网址 3' //================================================== var fruits = 'apple pear orange'; fruits.sub; // -> 'apple, pear orange' fruits.sub; // -> 'apple, pear orange' fruits.sub; // -> 'apple, pear, orange' fruits.sub(/w /, function{return match[0].capitalize; // -> 'Apple, Pear, orange' var markdown = '![a pear] ![an orange]'; markdown.sub/, function{ return '彩世界平台官方网址 4'; }); // -> '彩世界平台官方网址 5 ![an orange]' markdown.sub/, '彩世界平台官方网址 6'); // -> '彩世界平台官方网址 7 ![an orange]' interpolate() : 复制代码 代码如下: "#{animals} on a #{transport}".interpolate({ animals: "Pigs", transport: "Surfboard" }); //-> "Pigs on a Surfboard" scan() : 复制代码 代码如下: var fruits = []; 'apple, pear & orange'.scan(/w /, function{ fruits.push; fruits.inspect() // -> ['apple', 'pear', 'orange'] times() : 复制代码 代码如下: "echo ".times; //-> "echo echo echo " toQueryParams(): 复制代码 代码如下:'section=blog&id=45'.toQueryParams(); // -> {section: 'blog', id: '45'} 'section=blog;id=45'.toQueryParams(); // -> {section: 'blog', id: '45'} '); // -> {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}

本文由彩世界开奖app官网发布于彩世界平台官方网址,转载请注明出处:Prototype源码浅析 String部分之补充_prototype_脚本之

关键词: 脚本 源码 之家 Prototype