Reverse a String Alternative Help

Tell us what’s happening:
Why does my code return an array of 6 blank characters? I know the solution is to do “str.split(’’);” however, i wanted to accomplish the same by using regular expressions.

Your code so far

function reverseString(str) {
  return str.split(/\S/);
  
}

reverseString("hello");

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36.

Link to the challenge:
https://www.freecodecamp.org/challenges/reverse-a-string

The regex describes what you want the separator to be. You’ve set it to be any single non-space character, of which there are five in “hello”. If each character is a separator, then there’s an empty space before it and another one after. The result is that you’ve split the string into six empty strings.

So there is always an empty space character before the first letter of a word in a string?

No, not really. When you use a character as a separator in split, then you’re saying you want everything before and after that character to be in a new string, but not the character itself. Having a before and an after isn’t optional, though, so when you see an empty string it’s just because there was nothing to put into it. Consider this:

"hello".split("h"); // [ "", "ello"]

The character “h” is the separator, so we need a string before and after that point. There’s nothing that occurs before “h”, so the string doesn’t get filled. Everything after it gets put into the after string. You can see the same logic at work in

"hello".split("o"); // ["hell", ""]

In both cases, the before and after strings are created, but what is left in the original string to fill them with differs. When you split along all non-whitespace characters (\S), you’re turning every character in the string into a separator. In this case, the algorithm is a bit more complicated because the after string of one character can be the before string of the next character. Still, the logic is the same.

1 Like