2012-01-23 48 views
2

我要尋找一個Javascript正則表達式的應用程序我建立在jQuery的做:正則表達式 - 3個字母大寫

3個字母的單詞全部大寫:SRC到SRC 並以空格的下劃線:sub_1 = SUB 1

然後長於3個字母的任何字母成爲大寫的第一個字母:offer to offer。我得到了創建這些基礎的總體思路,但不確定將它們全部結合起來以表現任何想法的最佳方式?

  1. SRC到SRC
  2. sub_1到SUB_1
  3. 報價優惠

UPDATE,這是我現在有:

$('#report-results-table thead tr th').each(function(index) { 

      var text = $(this).html(); 

//   text = text.replace(/\n/gi, '<br />'); 
      text = text.replace(/_/gi, ' '); 
      text = text.replace(/((^|\W)[a-z]{3})(?=\W)/gi, function (s, g) { return g.toUpperCase(); }) 
      text = text.replace(/\w{4,255}(?=\W)/gi, function (s, g) { return s.charAt(0).toUpperCase() + s.slice(1); }) 


      $(this).html(text); 
    }); 

感謝

+2

爲說明您的規則稍有含糊,應當重新調整,包括3個字母后面的例外情況_ ##在這種情況下,他們應該遵循大寫的3字母規則。 –

+0

我應該澄清。 3個字母只是「src」,如果「sub_1」到「Sub 1」 – Coughlin

回答

3

該作品對我來說......

$.each(['this_1','that_1_and_a_half','my_1','abc_2'], function(i,v){ 
    console.log(
    v 
     // this simply replaces `_` with space globally (`g`) 
     .replace(/_/g,' ') 
     // this replaces 1-3 letters (`[a-zA-Z]{1,3}`) surrounded by word boundaries (`\b`) 
     // globally (`g`) with the captured pattern converted to uppercase 
     .replace(/\b[a-zA-Z]{1,3}\b/g,function(v){ return v.toUpperCase() }) 
     // this replaces lowercase letters (`[a-z]`) which follow a word boundary (`\b`) 
     // globally (`g`) with the captured pattern converted to uppercase 
     .replace(/\b[a-z]/g,function(v){ return v.toUpperCase() }) 
) 
}) 

爲了您的具體使用情況......

// loop through each table header 
$.each($('th'), function(i,v){ 
    // cache the jquery object for `this` 
    $this = $(this) 
    // set the text of `$this` 
    $this.text(
     // as the current text but with replacements as follows 
     $this.text() 
     .replace(/_/g,' ') 
     .replace(/\b[a-zA-Z]{1,3}\b/g,function(v){ return v.toUpperCase() }) 
     .replace(/\b[a-z]/g,function(v){ return v.toUpperCase() }) 
    ) 
}) 
+0

然後我會如何將它附加到我的文本中。我將循環遍歷一組要更新的元素。 – Coughlin

+0

發佈您的現有代碼,我無法猜測您獲得輸入的位置,或者您對輸出所做的操作。 –

+0

用我的代碼更新了我的問題 – Coughlin

相關問題