1

I looked at some other questions, haven't found one specific to this issue. Here is what I have:

function toCamelCase(str){
  const _str = str.split(/-|_/)

  for (let i = 0; i < _str.length; i++) {
    // if first character of string is capital,
    // make it Pascal Case, not Camel Case
    if (i === 0) {
      _str[i][0] =
        _str[i][0].match(/[A-Z]/)
          ? _str[i][0].toUpperCase()
          : _str[i][0].toLowerCase()
    } else {
      _str[i][0] = _str[i][0].toUpperCase()
    }
  }

  return _str.join("")
}

toCamelCase("This-is_a_test-string") // Thisisateststring

The output should be ThisIsATestString, but for some reason it is not working. What's weird is that the first if (i === 0) .. enters and assigns properly, but the rest doesn't work, even though it is entered.

Mike K
  • 7,621
  • 14
  • 60
  • 120
  • 1
    [strings are immutable](https://stackoverflow.com/questions/51185/are-javascript-strings-immutable-do-i-need-a-string-builder-in-javascript) – Calvin Nunes Nov 29 '19 at 12:20

2 Answers2

2

Why not use a replacement with a function for a single letter?

const toCamelCase = string => string.replace(/[_\-](.)/g, (_, g) => g.toUpperCase());

console.log(toCamelCase("This-is_a_test-string"));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Strings are immutable in Javascript. For example.

let a = "stackoverflow";

a[0] = a[0].toUpperCase(); // silently ignores 

a; // stackoverflow not Stackoverflow

a = "Stackoverflow";

a; // Stackoverflow; // you can point string to new value

In your code you are trying to change string values by using index:

str[i][0] = _str[i][0].match(/[A-Z]/) ? _str[i][0].toUpperCase() : _str[i[0].toLowerCase() 

This won't work cause the immutability of strings in JS.

Instead of that, you can change the whole string.

let a = "This-is_a_test-string";

let temp = a.split(/-|_/).map( (val)=>  val[0].match(/[A-Za-z]/)?  val[0].toUpperCase() + val.split("").slice(1).join("") : val );

console.log(temp.join(""));
Akshay Bande
  • 2,491
  • 2
  • 12
  • 29