user39980
user39980

Reputation:

Regex - 3 letters to caps

I am looking for a Javascript regex for an app I am building in jQuery to do:

3 letter words to all caps: src to SRC And any underscores to spaces: sub_1 = SUB 1

Then anything longer than 3 letters to be the first letter capitalized: offer to Offer. I get the overall idea to create the base of these, but not sure the best way to combine them all for performance any ideas?

  1. src to SRC
  2. sub_1 to SUB_1
  3. offer to Offer

UPDATE, this is what I have now:

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

Thanks

Upvotes: 2

Views: 493

Answers (1)

Billy Moon
Billy Moon

Reputation: 58531

This works for me...

$.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() })
  )
})

For your specific use case...

// 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() })
    )
})

Upvotes: 2

Related Questions