replace help

C

CK

Hi Guys,
I need a function that will replace the letter after a "hyphen" with a
capital letter.
Like if the user enter "Zeta-jones" it would be "Zeta-Jones".
I am a little stumped. Any ideas? I know it's a combination of substring
and replace and toUpper().
I just can't get the method call correctly.

I use iHyphen = x.indexOf("-");

I need to replace the letter after the hyphen with the uppercase version of
the letter.

Any ideas?
Thanks,
Chris
 
R

RobG

CK said:
Hi Guys,
I need a function that will replace the letter after a "hyphen" with a
capital letter.
Like if the user enter "Zeta-jones" it would be "Zeta-Jones".
I am a little stumped. Any ideas? I know it's a combination of substring
and replace and toUpper().
I just can't get the method call correctly.

I use iHyphen = x.indexOf("-");

I need to replace the letter after the hyphen with the uppercase version of
the letter.

You can use the following function based on a post from Baconbutty[1]:

var s="Zetta-jones-smith-walker";
var r=/(-)([a-z])/g;
s = s.replace(r,function(a,b,c){return '-' + c.toUpperCase();});
alert(s);

But note that it will not work in old browsers (or some newer ones), but
that is fixable (follow the thread down).

1.
<URL:
http://groups.google.co.uk/group/co...76ce21e48?q=camelCase&rnum=1#72776c776ce21e48
 
R

RobG

CK wrote:

Please dont' top-post.

Unfortunately that strips out the hyphens.

The original does, the version I posted doesn't (see below).

Thanks. Here's what I came up
with.

iHyphen = x.indexOf("-");
if(iHyphen > - 1)
{
output = x.replace(x.substr(iHyphen+1,
1),x.substr(iHyphen+1,1).toUpperCase());

}

If your hyphenated words may ever have more than one hyphen, or if the
first letter may not be already capitalised, then:

function hyCase(str)
{
var s=[], ss=str.split('-'), i=ss.length;
while ( i-- ){
s = ss.substr(0,1).toUpperCase() + ss.substr(1);
}
return s.join('-');
}

alert(hyCase('zetta-jones-smith-walker'));


may suit better.

[...]
You can use the following function based on a post from Baconbutty[1]:

var s="Zetta-jones-smith-walker";
var r=/(-)([a-z])/g;
s = s.replace(r,function(a,b,c){return '-' + c.toUpperCase();});
alert(s);

But note that it will not work in old browsers (or some newer ones), but
that is fixable (follow the thread down).

1.
<URL:
http://groups.google.co.uk/group/co...76ce21e48?q=camelCase&rnum=1#72776c776ce21e48
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top