正则表达式 - 3个字母的大写字母

时间:2012-01-23 13:24:49

标签: javascript jquery regex

我正在寻找一个Javascript正则表达式,用于我在jQuery中构建的应用程序:

所有大写的3个字母的单词:src到SRC 以及空格的任何下划线:sub_1 = SUB 1

然后,超过3个字母的任何内容都将成为首字母大写的:提议要约。我总体想法是创建这些的基础,但不确定将它们全部结合起来以表现任何想法的最佳方式?

  1. src to SRC
  2. sub_1到SUB_1
  3. 提议
  4. 更新,这就是我现在所拥有的:

        $('#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);
        });
    

    谢谢

1 个答案:

答案 0 :(得分: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() })
    )
})