How do I Capitalize First Letter of Each Word of a Field?

rhett1
Tera Expert

Is there a way that I can have an end-user enter a sentence into a normal string field and that each first letter of each word is made to be uppercase?

For example:

Risk no governance impacts the business.

TO:

Risk No Governance Impacts the Business.

1 ACCEPTED SOLUTION

WORKING Enhanced version that ignores capitalizing articles of the title:



function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue == '') {
          return;
    }


    var myText = newValue;
    var myTextInTitleCase = toTitleCase(myText);
    g_form.setValue('risk_name',myTextInTitleCase);


    function toTitleCase(e){
          var t=/^(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|vs?\.?|via)$/i;return e.replace(/([^\W_]+[^\s-]*) */g,
                function(e,n,r,i){
                      return r>0&&r+n.length!==i.length&&n.search(t)>-1&&i.charAt(r-2)!==":"&&i.charAt(r-1).search(/[^\s-]/)<0?e.toLowerCase():n.substr(1).search(/[A-Z]|\../)>-1?e:e.charAt(0).toUpperCase()+e.substr(1)
          }
    )};
}


View solution in original post

10 REPLIES 10

poyntzj
Kilo Sage

Once the user has entered their data, run it via this function and then replace the value




function toTitleCase(str)
{
  return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}


Thank you Julian.   Should this be a client script, a script include or something else?


Hello Julian,



What is "/\w\S*/g" in the script? Please explain.



Thanks,


Subhankar


Hello Subhankar,



That is regex. Its meaning is:


/\w\S*/g


  • \w match any word character [a-zA-Z0-9_]
  • \S* match any non-white space character [^\r\n\t\f ]
    • Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
  • g modifier: global. All matches (don't return on first match)

Check out this website. It's a great reference for building and understanding RegEx:


Online regex tester and debugger: JavaScript, Python, PHP, and PCRE