Skip to content Skip to sidebar Skip to footer

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,

Solution 1:

This should suit your needs:

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

Solution 2:

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

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

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

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

Post a Comment for "Capitalize Hyphenated Names In Javascript"