Eirik
Eirik

Reputation: 4205

Capitalize hyphenated names in javascript

I need to capitalize names in javascript and so far I've found these methods on SO:

// doesn't capitalize first letter after hyphen -> gives Bjørn-martin
str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });

// capitalizes after hyphen, but also after funny Norwegian characters (æøå) -> gives BjøRn-Martin
str.replace(/\b[\w']+\b/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });

// same as first
str = str.toLowerCase().replace(/^[\u00C0-\u1FFF\u2C00-\uD7FF\w]|\s[\u00C0-\u1FFF\u2C00-\uD7FF\w]/g, function(letter) {
    return letter.toUpperCase();
});

When trying to capitalize bjørn-martin none of them handles both funny Norwegian characters and hyphen.

I'm not exactly well versed in regex and was wondering if anyone could point me in the right direction so that bjørn-martin is correctly capitalized to Bjørn-Martin.

Upvotes: 1

Views: 4433

Answers (2)

sp00m
sp00m

Reputation: 48807

This should suit your needs:

var capitalized = input.replace(/(^|[\s-])\S/g, function (match) {
    return match.toUpperCase();
});

Upvotes: 12

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48590

Here is a configurable method. This will allow you to specify the word separators.

Pattern you need: /(^|-)(\w)/g

function transformToUpperCase(str, separators) {
  separators = separators || [ ' ' ];
  var regex = new RegExp('(^|[' + separators.join('') + '])(\\w)', 'g');
  return str.toLowerCase().replace(regex, function(x) { return x.toUpperCase(); });
}

document.body.innerHTML = transformToUpperCase('bjørn-martin', ['-']);

Upvotes: 3

Related Questions