1

I am trying to capitalize a character within a string in javascript, my codes are :

<button onclick="myFunction()">Try it</button> <script> function myFunction() { var str = "string"; for(m = 0; m < str.length; m++){ if(str[m] == "r"){ str[m+1] = str[m+1].toUpperCase(); } } alert(str); } </script> 

So what I am trying to do is, if the character is r,capitalize the next character. But is not woking means its the same string alerting.

2
  • 1
    AFAIR, I don't think you can modify it using str[x]=.... Use str.substring along with toUpperCase Commented May 19, 2014 at 6:16
  • There is a SO that seems to be the same question Here but I like @elclanrs' answer better... Commented May 19, 2014 at 6:20

4 Answers 4

6

Strings in JavaScript are immutable, you need to create a new string and concatenate:

function myFunction() { var str = "string"; var res = str[0]; for(var m = 1; m < str.length; m++){ if(str[m-1] == "r"){ res += str[m].toUpperCase(); } else { res += str[m]; } } } 

But you could simply use regex:

'string'.replace(/r(.)/g, function(x,y){return "r"+y.toUpperCase()}); 
Sign up to request clarification or add additional context in comments.

4 Comments

he wants the character after the r to be upper case, not the r
Oh I think I misunderstood the question a bit, thx @anishsane
@eclanrs He want to Capitalize the next character. Not "r"
@anishsane, yeah, but I wanted to demonstrate the callback, because the regex could be dynamic.
1

String are immutable. So You can convert string to array and do the replacements and then convert array to string. Array are mutable in Javascript.

var str = "string".split(''); for(m = 0; m < str.length - 1; m++){ if(str[m] == "r"){ str[m+1] = str[m+1].toUpperCase(); } } alert(str.join('')); 

Comments

0

Try this

<script> function myFunction() { var p=''; var old="r"; var newstr =old.toUpperCase(); var str="string"; while( str.indexOf(old) > -1) { str = str.replace(old, newstr); } alert(str); } </script> 

But you it will not work in alart. Hope it helps

2 Comments

Not "entire string".toUpperCase()... He wants a specific character to be upper cased.
sorry i edited the answer it will work now and @V.J alert can also show the uppercase string was my fault. please apologize my mistake.
0
var str = "string"; for(m = 0; m < str.length; m++){ // loop through all the character store in varable str. if(str[m] == "r") // check if the loop reaches the character r. { alert(str[m+1].toUpperCase()); // take the next character after r make it uppercase. } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.