Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 224
  • Last Modified:

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
0
danielamoura
Asked:
danielamoura
  • 2
1 Solution
 
mvan01Commented:
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:
http://www.experts-exchange.com/Web/Web_Languages/JavaScript/Q_21780040.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>

0
 
mvan01Commented:
Hi Daniel,

... then yours could look like this.

Peace and joy.  mvan

function ForceCorrectCase()
{
  var e = window.event;
    if (e.srcElement)
    {
      var pattern = /(\w)(\w*)/;
      var words =  e.srcElement.value.split(/\s+/g);
      for (i=0; i< words.length; i++)
      {
        var parts = words[i].match(pattern);
        var firstLetter = parts[1].toUpperCase();
        var restOfWord = parts[2].toLowerCase();
             words[i] = firstLetter + restOfWord;
       }
       e.srcElement.value = words.join(' ');
     }    
}
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now