Heim  >  Artikel  >  Web-Frontend  >  从jQuery.camelCase()学习string.replace() 函数学习_javascript技巧

从jQuery.camelCase()学习string.replace() 函数学习_javascript技巧

WBOY
WBOYOriginal
2016-05-16 18:02:181203Durchsuche

功能
camelCase函数的功能就是将形如background-color转化为驼峰表示法:backgroundColor。
此函数在jQuery的data函数,以及涉及到css的诸多函数中都有用到。

jQuery的实现

复制代码 代码如下:

//正则匹配
rdashAlpha = /-([a-z])/ig,
// camelCase替换字符串时的回调函数
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
...
camelCase: function( string ) {
return string.replace( rdashAlpha, fcamelCase );
},

这个功能本身并不难,就是调用了String对象的replace方法。但是本着学习的态度还是研究了一下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()参数说明
regexp:一个用于搜索正则表达式
substr:一个用于搜素字符串
newSubStr:一个用于替换的新字符串
function:一个回调函数,函数的返回值用于替换原匹配的字符串
flags:非标准,类似于RegExp的i、g、m(忽略大小写、是否全局搜索、匹配多行)

指定字符串作为替换对象
在用于替换的字符串中你可以使用以下模式:
$$ => 插入一个$
$& => 插入匹配的子串
$` =>插入匹配的子串之前的所有字符
$' => 插入匹配的子串之后的所有字符
$n / $nn => 此模式只有在replace()方法的第一个参数为RegExp,且正则表达式内包含括号时有效。

指定函数作为替换对象
典型的replacement函数:function(str,p1,p2,offset,s){}
参数说明:
str:匹配的字符串(类似$&)
p1,p2,...:此模式只有在replace()方法的第一个参数为RegExp,且正则表达式内包含括号时有效。(类似$n / $nn)
offset:匹配子串的偏移量
s:用于搜索的字符串

获取CSS属性的驼峰表示
复制代码 代码如下:

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();

交换匹配字符串的位置
复制代码 代码如下:

var re = /(\w+)\s(\w+)/;
var str = "John Smith";
var newstr = str.replace(re, "$2, $1");
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn