Link to home
Create AccountLog in
Avatar of danielamoura
danielamoura

asked on

Split words with more than one separator

I need to make sure all my fields are written with what we are calling Correct Case. It means first letter upper, and all other letters on lowercase.
I have the following code that is being executed on the keyupevent of some text input fields. This code works, but does not treat cases where the word separator is a period :

function ForceCorrectCase()
{
   var e = window.event;
    if (e.srcElement)
    {
      var words =  e.srcElement.value.split(' ');
      var dst='';
      var len = 0;
      for (i=0; i< words.length; i++)
      {
         dst += words[i].charAt(0).toUpperCase() + words[i].substring(1,words[i].length).toLowerCase();
         len += words[i].length;
       
         if ( (i+1) != words.length) //do not add spaces to last word
              dst += ' ';
       }
       e.srcElement.value = dst;
     }    
}

I tired using regular expressions for my split, but I'm not very familiar with regular expressions and it didn't work.
Any ideas?
Thanks
Avatar of mvan01
mvan01
Flag of United States of America image

Hi Daniel,

Here's some help.  Regular expressions can split strings on word boundaries, which include white space (space, tab) and comma and period.

Here's an example trying to do the same as you are, from:
https://www.experts-exchange.com/questions/21780040/Need-Sentence-Case-not-ProperCase-Please.html

It's not tied to the text box, but you know how to do that, given your example above.

Peace and joy.  mvan


<script language="javascript">
function firstLetterUpper(fml) {
    var pattern = /(\w)(\w*)/;
    var a = fml.value.split(/\s+/g);
    for (i = 0 ; i < a.length ; i ++ ) {
        var parts = a[i].match(pattern);
        var firstLetter = parts[1].toUpperCase();
        var restOfWord = parts[2].toLowerCase();
             a[i] = firstLetter + restOfWord;
    }
    fml.value = a.join(' ');
}
</script>

ASKER CERTIFIED SOLUTION
Avatar of mvan01
mvan01
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer