"Evertjan." <exjxw.hannivoort@interxnl.net> writes:
[color=blue]
> Fox wrote on 11 nov 2003 in comp.lang.javascript
:
>[color=green]
>> String.prototype.ucwords = function(){
>> return this.replace(/\b\w/gi, function(c,i,s) { return
>> c.toUpperCase(); });
>> }
>>[/color]
>
> String.prototype.ucwords = function(){
> return this.toLowerCase().replace(/\b\S/g, function(x) { return
> x.toUpperCase(); });
> }[/color]
Your version would uppercase[1] any non-space letter after a word
boundary. The previous version uppercased all word characters after
a word boundary. Since word characters includes all letters, and only
letters can be meaninfully uppercased, there isn't any significant difference.
[color=blue]
> The rest has to be lowercase, IMHO.[/color]
What rest? Your RegExp matches more characters than the previous one.
[color=blue]
> I do not think the i in /gi is necessary.[/color]
Correct, \w matches both upper- and lowercase letters already.
[color=blue]
> Why replace the whole word?[/color]
It doesn't, it only replaces one character at a time. The \w code
matches *one* word character, not an entire word.
[color=blue]
> Please explain for us mortals what the (c,i,s) does ![/color]
From ECMA-262 section 15.5.4.11:
---
If /replaceValue/ is a function, then for each matched substring, call
the function with the following m + 3 arguments. Argument 1 is the
substring that matched. If /searchValue/ is a regular expression, the
next m arguments are all of the captures in the /MatchResult/ (see
15.10.2.1). Argument m + 2 is the offset within /string/ where the
match occurred, and argument m +3 is /string/. The result is a string
value derived from the original input by replacing each matched
substring with the corresponding return value of the function call,
converted to a string if need be.
---
I.e.,
c is the current match
and since the regExp doesn't contain capturing parentheses (m==0),
i is the offset of the match in the original string, and
s is the original string.
/L
--
Lasse Reichstein Nielsen -
lrn@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'