发布于 2016-08-21 08:18:18 | 125 次阅读 | 评论: 0 | 来源: 网友投递


下面介绍Prototype对String对象的扩展部分:

这部分主要为string对象添加了几个很有用的方法:

strip(): 去掉字符串两边的空白, 例如"  jj  ".strip()返回"jj"
stripTags():去掉字符串中的html标签
stripScripts(): 去掉字符串中的javascript代码段
extractScripts(): 返回字符串中的javascript代码,返回数组
evalScripts(): 执行字符串中的javascript代码
escapeHTML():将字符串中的html代码转换为可以直接显示的格式, 例如将< 转化为<,在ie6中有bug,执行这个操作返回的字符串,将多个连在一起的空白变成了一个,所以很多换行什么的都被去掉了
unescapeHTML(): escapeHTML的反向过程
truncate(length, truncation): 截断,例如"abcdefghigkl".truncate(10)返回abcdefg..., truncation默认为"..." toQueryParams(separator)/parseQuery(separator):将一个querystring转化为一个hash表(其实是一个对象,在javascript中对象可以当成hash表来用,因为对象的属性或方法可以通过object[propertyName]来访问)
toArray(): return this.split(''), 转化为一个字符数组
camelize(): 将background-color的形式转化为backgroundColor形式,用在style/css中
capitalize(): 返回一个首字母大写的字符串
inspect(useDoubleQuotes): 返回字符串的表示形式, 例如"sdfj\"sfa".inspect() 返回 “'sdfj"sfa'”
gsub(pattern, replacement):pattern是一个正则表达式,replacement是一个函数(或者是一个template字符串),对于字符串中每个匹配pattern的部分使用replacement处理,然后将replacement返回的值将原来匹配的部分替换掉,例如"skdjfAsfdjkAdk".gsub(/A/,function(match){return match[0].toLowerCase()}), 将字符串所有的A转化为a, 注意pattern中不要添加g选项,因为gsub会递归的执行match方法
sub(pattern, replacement, count) :gsub的另一种形式,不过可以设置执行的次数
scan(pattern, iterator): 跟gsub差不多,但是返回的是字符串本身,也就是说对于pattern中的每个匹配执行iterator,但是不返回替换的字符串"skdjfAsfdjkAdk".gsub(/A/,function(){alert 'have a A'})
underscore(): 'borderBottomWidth'.underscore()  -> 'border_bottom_width'
dasherize(): 'Hello_World'.dasherize()  -> 'Hello-World'
Template模板类:
使用方法:
var template = new Template(replacement, pattern);                
template.evaluate(object) 有点像php中的模板,默认(没有提供pattern)将{propertyName}形式的东西替换了object的属性值

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务