Search code examples
javascriptstringif-statementwhitespacecharat

If whitespace not working properly with charAt


In this code I get a random string from the site codeHs, what I have to Do is create a program to return the random string like this, if str was = hello this will be the output --> Hello then hEllo then heLlo then helLo then hellO, Its also supposed to skip whitespaces and just go to the next variable

my current code is

function wave(str){
  var str2 = [];
  var j = 0;
  for (var i = 0; i < str.length; i++, j++)
    {
      if (!/^\s*$/.test(str.charAt(i)))
        {
          str2[j] =  str.slice(0, i) + str.charAt(i).toUpperCase() + str.slice(i + 1)
        }
      else if (i + 1 < str.length)
        {
          i += 1;
          str2[j] =  str.slice(0, i) + str.charAt(i).toUpperCase() + str.slice(i + 1)
        }
    }
  console.log(str2)
  console.log(str.length)
  return str2;
  
}

when i run it on test mode it gives me

this is the image

when i run it on attempt mode it gives me

this is the image

It's fine with the basic test but it doesn't work with the random test this is the error and I don't know how to fix it, it looks like it's an error with the if statement not triggering correctly

enter image description here


Solution

  • The issue you're facing is when there are two spaces in a row. Your problem is that in your else block, you're assuming that if you encounter a space, then the next character won't be a space, and pushing that into str2 (resulting in the word containing no uppercase letters, as you just pushed a new item by trying to capitalize a space).

    Instead, remove the else block entirely. It's not needed as you'll handle the next non-space character once you eventually reach it in your loop, don't try and handle the next character in advance, as your loop will do that for you when you get to it. Note that you now only need to increase j when you add a transformed word to your array, not on every iteration

    function wave(str) {
      var str2 = [];
      var j = 0;
      for (var i = 0; i < str.length; i++) {
        if (!/^\s*$/.test(str.charAt(i))) {
          str2[j] = str.slice(0, i) + str.charAt(i).toUpperCase() + str.slice(i + 1);
          j++;
        }
      }
      return str2;
    }
    
    console.log(wave("hello"));
    console.log(wave("abc  efg"));

    The above code can be simplified to remove the regex check and the j counter by using .push():

    function wave(str) {
      var result = [];
      for (var i = 0; i < str.length; i++) {
        if (str.charAt(i) != " ") { // or just str[i] != " "
          result.push(str.slice(0, i) + str.charAt(i).toUpperCase() + str.slice(i + 1));
        }
      }
      return result;
    }
    
    console.log(wave("abc  efg"));