Nitish
Nitish

Reputation: 2763

Make a character capitalize within a strin in javascript not working

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.

Upvotes: 1

Views: 129

Answers (4)

Fizer Khan
Fizer Khan

Reputation: 92875

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(''));

Upvotes: 1

Shakeel
Shakeel

Reputation: 21

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.
        }
    }

Upvotes: 0

Najib
Najib

Reputation: 520

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

Upvotes: 0

elclanrs
elclanrs

Reputation: 94121

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()});

Upvotes: 6

Related Questions