2

I have this regex (dug up form somewhere)

return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});

that Capitalizes the First Characters of a Prsons name.

It does not handle a Hyphanated Name like

melinda-ann smith

and returns

Melinda-ann Smith

when it should be

Melinda-Ann Smith

Regex is a very weak point with me, ... What do I need to change to Capitalize the character after the hyphen.

Mark Cupitt
  • 180
  • 12

3 Answers3

3

Found the Solution

str.replace(/\b[\w']+\b/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});

works just fine .

Mark Cupitt
  • 180
  • 12
1

I would recommend for this purpose not to use such procedural language and use more functional and more extendabale.

This function makes capitalization of first letter in regular and hyphened names(including with 'minus' sign or 'hyphen' -> [- –])

const startCase = (string) => 
  _.compact(string.split(' '))
          .map((word) => word.split(/[-–]/).map(_.capitalize).join('-'))
          .join(' ') // "melinda-ann smith" -> "Melinda-Ann Smith"
Mihey Mik
  • 1,643
  • 13
  • 18
  • 2
    Would be nice if you can explain what your code is doing and how it address the OP question. – рüффп May 17 '17 at 10:43
  • this code makes capitalization of first letter in regular and hyphened names(including with 'minus' sign or 'hyphen' -> [- –]). I believe it is more functionally correct - then the making it as in the question with str.replace(....) – Mihey Mik May 18 '17 at 07:08
  • You should edit your answer instead putting the detail in comment. [Example of a good answer referring the doc](http://stackoverflow.com/a/17320218/628006) – рüффп May 18 '17 at 09:58
  • is it better now? – Mihey Mik May 19 '17 at 06:56
  • yes sure it is always best to explain and document as much as possible your answers with code even if sometimes it can be easy or obvious for experienced developers, probably beginners can still like to have the "why". – рüффп May 24 '17 at 10:50
0

Inorder to make it capitalize, first non-uppercase letter like this:

'~\b([a-z])~'

it make melinda-ann smith to Melinda-Ann Smith