String 扩展

camelize():运用在Selector中,将一些Css属性和其他的特殊字符串转化成一个统一的格式

'background-color'.camelize();//->'backgroundColor'
'-moz-binding'.camelize();//->'MozBinding'

//该方法实现
...
camelize: function() {
    var parts = this.split('-'), len = parts.length;
    if (len == 1) return parts[0];

var camelized = this.charAt(0) == '-'
    ? parts[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():将首字母大写,其他字母小写(汉字不变)

dasherize():将"_"替换为"-"

'border_bottom_width'.dasherize();//->'border-bottom-width'

'borderBottomWidth'.underscore().dasherize();//->'border-bottom-width'

escapeHTML():将HTML标签字符转化为可以显示的字符, 非常像.Net中的 Server.HtmlEncode()

'<div class="article">Thisisanarticle</div>'.escapeHTML();
//->"&lt; div class="article" &gt; This is an article &lt; /div &gt;"

evalScript():evalScripts()->[returnedValue...]执行字符串中的Javascript

'lorem...<script>2+2</script>'.evalScripts();
//->[4]
'<script>2+2</script><script>alert("helloworld!")</script>'.evalScripts();
//->[4,undefined](and displays 'helloworld!' in the alert dialog)

extractScript():extractScripts()->[script...]提取Javascript

'lorem...<script>2+2</script>'.extractScripts();
//->['2+2']

'<script>2+2</script> <script>alert("hello world!")</script>'.extractScripts();
//->['2+2','alert("helloworld!")']

//提取并执行
var myScripts='<script>2+2</script><script>alert("helloworld!")</script>'.extractScripts();
//->['2+2','alert("helloworld!")']
var myReturnedValues=myScripts.map(function(script){
      return eval(script);
});
//->[4,undefined](and displays 'helloworld!'in the alert dialog)

gsub():gsub(pattern,replacement)->string,replace()函数不用正则表达式只会替换一次,这个函数不仅可以按照的正则表达式全部替换,而且...请看

var mouseEvents='click dblclick mousedown mouseup mouseover mousemove mouseout';
mouseEvents.gsub('',',');
//->'click,dblclick,mousedown,mouseup,mouseover,mousemove,mouseout'
mouseEvents.gsub(/\s+/,',');
//->'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='![apear](/img/pear.jpg)![anorange](/img/orange.jpg)';
markdown.gsub(/!\[(.*?)\]\((.*?)\)/,function(match){
    return'<img alt="'+match[1]+'"src="'+match[2]+'"/>';
});
//->'<img alt="a pear"src="/img/pear.jpg"/><img alt="an orange" src="/img/orange.jpg"/>'

markdown.gsub(/!\[(.*?)\]\((.*?)\)/,'<imgalt="#{1}"src="#{2}"/>');
//->'<img alt="a pear" src="/img/pear.jpg"/><img alt="an orange" src="/img/orange.jpg"/>'

//最后提醒在正则表达式中不要使用'g'否则回死循环

inspect():inspect([useDoubleQuotes=false])->String,看例子

'I\'m so happy.'.inspect();
//->'\'I\\\'m so happy.\''(displayed as 'I\'msohappy.' in an alert dialog or the console)

'I\'m so happy.'.inspect(true);
//->'"I'm so happy."'(displayed as "I'msohappy." in an alert dialog or the console)

parseQuery():toQueryParams([separator='&'])->Object,又名toQueryParam(),将形似"opt1=value1&opt2=value2"的字符串转化为Json

'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%20on%20rails'}  还可以编码

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

scan():scan(pattern,iterator)->String,正则表达式迭代

'apple pair & banana'.scan(/\w+/,function(str){alert(str);});
//output alert 3 times: apple pair banana

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

'failure-message,success-message & spinner'.scan(/(\w|-)+/,Element.toggle)
//->'failure-message,success-message&spinner'toggle these three elements

strip():去除左边和右边的空格

'   hello world!  '.strip();
//->'hell oworld!'

stripScript():去除Javascript

'a <a href="#">link</a><script> alert("helloworld!")</script>'.stripScripts();
//->'a <ahref="#">link</a>'

stripTags():去除HTML标签(包括script标签,但是会执行Javascript)

'a <a href="#">link</a>'.stripTags();
//->'a link'
'a <a href="#">link</a><script>alert("helloworld!")</script>'.stripTags();
//->'a link alert("hello world!")'
'a <ahref="#">link</a><script>alert("helloworld!")</script>'.stripScripts().stripTags();
//->'a link'

sub():sub(pattern,replacement[,count=1])->string替换,用repalce()函数只能替换一次,参数count是指替换匹配的次数

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='![apear](/img/pear.jpg)![anorange](/img/orange.jpg)';
markdown.sub(/!\[(.*?)\]\((.*?)\)/,function(match){
return '<img alt="'+match[1]+'" src="'+match[2]+'"/>';
});
//->'<img alt="apear" src="/img/pear.jpg"/>![an orange](/img/orange.jpg)'

markdown.sub(/!\[(.*?)\]\((.*?)\)/,'<img alt="#{1}"src="#{2}"/>');
//->'<img alt="apear" src="/img/pear.jpg"/>![an orange](/img/orange.jpg)'

succ():succ()->string  最后一个字符的ASCII自增

'a'.succ();
//->'b'
'aaaa'.succ();
//->'aaab'

toArray():转换成Array

'a'.toArray();
//->['a']
'hello world!'.toArray();
//->['h','e','l','l','o',' ','w','o','r','l','d','!']

truncate():truncate([length=30[,suffix='...']])->string,将长字符串截成length-suffix.length,并在字符串末尾添上suffix,长度不够不变换,这个函数很有用,显示标题之类的情况下,往往地方有限制,这样可以巧妙的截取字符串

'A random sentence whose length exceeds 30 characters.'.truncate();
//->'A random sentence whose len...'
'Some random text'.truncate();
//->'Some random text.'
'Some random text'.truncate(10);
//->'Some ra...'
'Some random text'.truncate(10,'[...]');
//->'Some[...]'

underscore():与camlize()功能相反

'borderBottomWidth'.underscore(); // -> 'border_bottom_width'

'borderBottomWidth'.underscore().dasherize(); // -> 'border-bottom-width'


unescapeHTML(): 将编码的标签字符还原

'x&gt;10'.unescapeHTML()
//->'x>10'
'<h1>Pride &amp; Prejudice</h1>'.unescapeHTML()
//->'Pride & Prejudice'