欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

從jQuery.camelCase()學(xué)習(xí)string.replace() 函數(shù)學(xué)習(xí)

 更新時間:2011年09月13日 22:54:02   作者:  
camelCase函數(shù)的功能就是將形如background-color轉(zhuǎn)化為駝峰表示法:backgroundColor。
功能
camelCase函數(shù)的功能就是將形如background-color轉(zhuǎn)化為駝峰表示法:backgroundColor。
此函數(shù)在jQuery的data函數(shù),以及涉及到css的諸多函數(shù)中都有用到。

jQuery的實現(xiàn)
復(fù)制代碼 代碼如下:

//正則匹配
rdashAlpha = /-([a-z])/ig,
// camelCase替換字符串時的回調(diào)函數(shù)
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
...
camelCase: function( string ) {
return string.replace( rdashAlpha, fcamelCase );
},

這個功能本身并不難,就是調(diào)用了String對象的replace方法。但是本著學(xué)習(xí)的態(tài)度還是研究了一下replace方法。
資料參考:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace

String.replace()語法
str.replace(regexp|substr, newSubStr|function[, Non-standard flags]);

String.replace()參數(shù)說明
regexp:一個用于搜索正則表達(dá)式
substr:一個用于搜素字符串
newSubStr:一個用于替換的新字符串
function:一個回調(diào)函數(shù),函數(shù)的返回值用于替換原匹配的字符串
flags:非標(biāo)準(zhǔn),類似于RegExp的i、g、m(忽略大小寫、是否全局搜索、匹配多行)

指定字符串作為替換對象
在用于替換的字符串中你可以使用以下模式:
$$ => 插入一個$
$& => 插入匹配的子串
$` =>插入匹配的子串之前的所有字符
$' => 插入匹配的子串之后的所有字符
$n / $nn => 此模式只有在replace()方法的第一個參數(shù)為RegExp,且正則表達(dá)式內(nèi)包含括號時有效。

指定函數(shù)作為替換對象
典型的replacement函數(shù):function(str,p1,p2,offset,s){}
參數(shù)說明:
str:匹配的字符串(類似$&)
p1,p2,...:此模式只有在replace()方法的第一個參數(shù)為RegExp,且正則表達(dá)式內(nèi)包含括號時有效。(類似$n / $nn)
offset:匹配子串的偏移量
s:用于搜索的字符串

獲取CSS屬性的駝峰表示
復(fù)制代碼 代碼如下:

String.prototype.camelCase=function(){
//all為匹配的子串,而letter則為p1,因為[a-z]加入了括號
return this.replace(/-([a-z])/ig,function( all, letter,offset,s ) {
return letter.toUpperCase();
});
};
var cssText = 'h2\n{\n border-bottom:1px solid #eee;\n background-color:#bbb;\n}';
var newstr = cssText.camelCase();

交換匹配字符串的位置
復(fù)制代碼 代碼如下:

var re = /(\w+)\s(\w+)/;
var str = "John Smith";
var newstr = str.replace(re, "$2, $1");

相關(guān)文章

最新評論