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