0

I've found a nice RegExp to transform "lower case name" to "Title Case Name" but I've noticed that it doesn't works correctly with French names like "Jean-Marie" that should stay and not transformed into "Jean-marie" and so on.

So, here it is the whole function with the RegExp:

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

So, the question: How can I modify the RegExp to take care also of the French names?

Thanks a lot for the answers!

Francesco Piraneo G.
  • 882
  • 3
  • 11
  • 25
  • It doesn't look like you've made an attempt to solve this yourself. Please show a [mcve] of what you've attempted otherwise this is [off-topic (#1)](/help/on-topic). – zzzzBov Jan 19 '18 at 16:24

2 Answers2

1

This works. For more info refer this

The following regex also works for normal cases. vignesh raja = Vignesh Raja

var name = "vignesh-raja";
name = name.replace(/\b\w+/g, function(str) {
  return str.charAt(0).toUpperCase() + str.substr(1);
});
console.log(name);
Vignesh Raja
  • 7,927
  • 1
  • 33
  • 42
0

The replace method can take a function as the second parameter with a number of parameters..

From the docs:

p1, p2, ...

The nth parenthesized submatch string, provided the first argument to replace() was a RegExp object. (Corresponds to $1, $2, etc. above.) For example, if /(\a+)(\b+)/, was given, p1 is the match for \a+, and p2 for \b+.

What you could do is use a regex like (\w)(\w+(?:-\w+)*) which will match words with a hyphen as 1 word. Then you could capture the first character in the first group, and the rest of the match in the second group.

Then use toUpperCase to convert that character and return the concatenated name.

For example:

function titleCase(source) {
  return source.replace(/(\w)(\w+(?:-\w+)*)/g, function(txt, p1, p2) {
    return p1.toUpperCase() + p2.toLowerCase();
  });
}

var titles = [
  "lower case name",
  "Jean-Marie",
  "JEAN-MARIE",
  "tEST TEST-TEST tesT"
];
for (var i = 0; i < titles.length; i++) {
  console.log(titles[i] + " ---> " + titleCase(titles[i]));
}

Note

Using \w for names matches [A-Za-z0-9_]

The fourth bird
  • 154,723
  • 16
  • 55
  • 70