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.

Nitish
  • 2,695
  • 9
  • 53
  • 88
  • 1
    AFAIR, I don't think you can modify it `using str[x]=...`. Use `str.substring` along with `toUpperCase` – anishsane May 19 '14 at 06:16
  • There is a SO that seems to be the same question [Here](http://stackoverflow.com/questions/1431094/how-do-i-replace-a-character-at-a-particular-index-in-javascript) but I like @elclanrs' answer better... – Ballbin May 19 '14 at 06:20

4 Answers4

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()});
anishsane
  • 20,270
  • 5
  • 40
  • 73
elclanrs
  • 92,861
  • 21
  • 134
  • 171
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(''));
Fizer Khan
  • 88,237
  • 28
  • 143
  • 153
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

Najib
  • 500
  • 2
  • 8
  • 2
    Not `"entire string".toUpperCase()`... He wants a specific character to be upper cased. – anishsane May 19 '14 at 06:20
  • 1
    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. – Najib May 19 '14 at 06:49
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.
        }
    }
Shakeel
  • 21
  • 2