2012-01-23 51 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

相关问题