DIV CSS 佈局教程網

從 jQuery camelCase 理解 String.replace 的用法
編輯:關於JavaScript     

jQuery 的 camelCase 常把 background-color 轉成 backgroundColor,方便操作 CSS 屬性。其核心是 String.replace 搭配正則與回呼函式。

基本實作

var rdashAlpha = /-([a-z])/ig;
function fcamelCase(all, letter) {
  return letter.toUpperCase();
}
var result = 'background-color'.replace(rdashAlpha, fcamelCase);

replace 參數

replace 的第一個參數可以是字串或正則,第二個參數可以是替換字串或函式。若使用函式,參數依序為匹配內容、各個捕獲群組、偏移量與原始字串。

常見替換符號

  • $$ 插入 $
  • $& 插入匹配子字串
  • $` 插入匹配前的內容
  • $' 插入匹配後的內容
  • $n 插入第 n 個捕獲群組

擴充 camelCase

String.prototype.camelCase = function () {
  return this.replace(/-([a-z])/ig, function (all, letter) {
    return letter.toUpperCase();
  });
};
var cssText = 'background-color';
var newStr = cssText.camelCase();

另一個常見技巧是交換符合片段的順序,例如把 John Smith 轉成 Smith, John:

var re = /(\w+)\s(\w+)/;
var str = 'John Smith';
var newStr = str.replace(re, '$2, $1');
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved