the_lone_note
the_lone_note

Reputation: 161

upper case both last name when there is a dash in between

I would like to modify an existing JavaScript function that formats a user name properly by setting the first name first letter to upper case, as well as the first name of the last name.

There are some last names that are hyphenated and when those happen, they look like Hugo Bearsotti-potz, when in fact it should be Hugo Bearsotti-Potz

I would like to ask for help to modify this function so it allows proper case to hyphenated last names, if possible.

Here is the existing code (pertinent snippet only):

        if (input) {
            var out = '';
            input.split(delimiter || ' ').forEach(function (sector) {
                var x = sector.toLowerCase();
                out += x.charAt(0).toUpperCase() + x.substr(1) + ' ';
            });
            if (out.length > 0) {
                out = out.substring(0, out.length - 1);
            }
            return out;
        }

Many thanks.

Upvotes: 1

Views: 292

Answers (2)

csbarnes
csbarnes

Reputation: 1893

You could also create a function for capitalizing the first character after any given delimiter. Not quite as succinct as the regex solution though.

function capitalizeAfter(input, delimiter) {
  var output = '',
      pieces = input.split(delimiter);

  pieces.forEach(function(section, index) {
    // capitalize the first character and add the remaining section back
    output += section[0].toUpperCase() + section.substr(1);

    // add the delimiter back if it isn't the last section
    if (index !== pieces.length - 1) {
      output += delimiter;
    }
  }
  return output;
}

Then it would be used like so:

if (input) {
  return capitalizeAfter(capitalizeAfter(input.toLowerCase(), ' '), '-');
}

Upvotes: 1

wesww
wesww

Reputation: 2873

this should satisfy your test conditions set: http://plnkr.co/edit/9welW6?p=preview

html:

<input type="text" ng-model="foo">
<br>
{{foo | nameCaps}}

js:

app.filter('nameCaps',function(){
  return function(input) {
    if (!input) return;
    return input.toString().replace(/\b([a-z])/g, function(ch) {
      return ch.toUpperCase();
    });
  };
});

although I'm wary about making assumptions about people's names http://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/

Upvotes: 2

Related Questions