Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
19
rated 0 times [  26] [ 7]  / answers: 1 / hits: 71931  / 13 Years ago, thu, may 26, 2011, 12:00:00

I'd like to know how to replace a capture group with its uppercase in JavaScript. Here's a simplified version of what I've tried so far that's not working:



> a=foobar
'foobar'
> a.replace( /(f)/, $1.toUpperCase() )
'foobar'
> a.replace( /(f)/, String.prototype.toUpperCase.apply($1) )
'foobar'


Would you explain what's wrong with this code?


More From » regex

 Answers
9

You can pass a function to replace.



var r = a.replace(/(f)/, function(v) { return v.toUpperCase(); });


Explanation



a.replace( /(f)/, $1.toUpperCase())


In this example you pass a string to the replace function. Since you are using the special replace syntax ($N grabs the Nth capture) you are simply giving the same value. The toUpperCase is actually deceiving because you are only making the replace string upper case (Which is somewhat pointless because the $ and one 1 characters have no upper case so the return value will still be $1).



a.replace( /(f)/, String.prototype.toUpperCase.apply($1))


Believe it or not the semantics of this expression are exactly the same.


[#92030] Wednesday, May 25, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anikas

Total Points: 258
Total Questions: 102
Total Answers: 95

Location: Monaco
Member since Sun, Jan 16, 2022
2 Years ago
;