-1

I am trying to convert a name string 'talhakhan' to 'TaLhaKhAn'. I can loop through the entire variable but I am facing issue in assignment. Please check my code:

var name = 'talhakhan';
var counter = true;
for (var e = 0; e < name.length; e++) {
  if (counter)
    name.charAt(e) = name.charAt(e).toUpperCase();
  else
    name.charAt(e) = name.charAt(e).toLowerCase();
  counter = false;
}

error:

VM704:1 Uncaught ReferenceError: Invalid left-hand side in assignment at :1:11

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • 5
    `name.charAt(e)` calls a function which returns a value. You can't assign a value to a function call. – ADyson Oct 06 '21 at 11:10
  • 2
    Generally, strings are *immutable*, you cannot assign to a specific letter in a string. You need to concatenate into a new string. – deceze Oct 06 '21 at 11:12
  • 1
    [`String.charAt()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt) returns a new string, not a reference to a certain character of the original string. Your statement is the same as `'a' = 'a'.toUpperCase();`. `'a'` is a constant, it cannot be assigned a new value. – axiac Oct 06 '21 at 11:16
  • `TaLhaKhAn` or `TaLhAkHaN`? That would make more sense. There seems no reason why you had `ha` as consecutive lower-case letters in your example. I based my answer on what I think is probably what you meant. – ADyson Oct 06 '21 at 11:37

2 Answers2

2

name.charAt(e) calls a function which returns a value. You can't assign a value to a function call.

You can assign a value to a variable though. Simply build up a new string with the altered values. Your logic with counter also needed amending as in your version it would always be false after the first character.

Demo:

var name = 'talhakhan';
var counter = true;
var newname = "";
for (var e = 0; e < name.length; e++) {
  if (counter) {
    newname += name.charAt(e).toUpperCase();
    counter = false;
  }
  else {
    newname += name.charAt(e).toLowerCase();
    counter = true;
  }
}

alert(newname);
ADyson
  • 57,178
  • 14
  • 51
  • 63
0

I guess you want to produce TaLhAkHaN and not TaLhaKhAn judging by your code sample…

You can split the string, apply your transformation and join back into a string. (this will break special characters made of surrogate pairs)

let name = 'talhakhan';
name = name.split('').map((character, i) =>
  (i % 2) ? character.toUpperCase() : character.toLowerCase()
).join('')
console.log(name)
thchp
  • 2,013
  • 1
  • 18
  • 33