2

I am trying to do the equivalent of PHP's ucwords() in Flex. I dont want the whole string in uppercase just the first letter of each word. Does anyone know a way?

Thanks!

JD Isaacks
  • 56,088
  • 93
  • 276
  • 422

5 Answers5

11

Try

str.replace(/\b./g,function(m){return String(m).toUpperCase()});

explanation:

the regex /\b./g matches a word boundary followed by any character. All matches will be passed to the anonymous function defined in second parameter of replace method. The function returns the match capitalized.

JD Isaacks
  • 56,088
  • 93
  • 276
  • 422
Rafael
  • 18,349
  • 5
  • 58
  • 67
10

This is the same as Rafael's answer but with no warnings :)

str.replace(/\b./g,function(...m):String{return m[0].toUpperCase()});
JD Isaacks
  • 56,088
  • 93
  • 276
  • 422
1

The accepted answer assumes that the string is all lower-case to start with. If you start with a string with all upper-case or random mixed-cases, this will not work.

Here is a simple modification that does not require the source string to be all lower-case to begin with:

str.toLowerCase().replace(/\b./g,function(...m):String{return m[0].toUpperCase()});
Irvin Dominin
  • 30,819
  • 9
  • 77
  • 111
Evan de la Cruz
  • 1,966
  • 1
  • 13
  • 17
1

I had some problems with special characters in Portuguese, so I changed it to this RegExp:

str.replace(/(^|\s|\t)+\S/g, function(...m):String{return m[0].toUpperCase()});
André Gil
  • 624
  • 7
  • 13
0

I made the following changes to get past some errors and warnings:

str.replace(/\b./g,function(m:String):String{return m.toUpperCase()});

but it gave me a strange crash, saying that it had three parameters when only one was expected.

I tried to fix the regex, but my regex-fu is not great. So I punted. This works (at least, for the first word in a string). For multiple words, you'd have to use the split.

str = str.substr(0,1).toUpperCase() + str.substr(1,str.length);

  • I got the same error when I tried to do that too, but leaving it the way Rafael made it works. – JD Isaacks May 20 '09 at 13:39
  • I finally figured out how to make this work without any errors or warnings: str.replace(/\b./g,function(...m):String{return m[0].toUpperCase()}); – JD Isaacks Jan 07 '10 at 22:02