Undefined in Split String

Viewed 95

i have a function to split string into 2 part, front and back. Then reverse it to back and front. Here is my code

function reverseString(string) {
    let splitString = ""
    let firstString = ""

    for(i = 0; i <= string.length/2 - 1; i++) {
        firstString += string[i]
    }

    for(i = string.length/2; i <= string.length; i++) {
        splitString += string[i]
    }
    return splitString + firstString
}

Sorry for bad explanation, this is test case and expected result (first one is expected result, the second one is my result)

console.log(reverseString("aaabccc")); // "cccbaaa" "undefinedundefinedundefinedundefinedaaa"
console.log(reverseString("aab")); // "baa" "undefinedundefineda"
console.log(reverseString("aaaacccc")); // "ccccaaaa" "ccccundefinedaaa"
console.log(reverseString("abcdefghabcdef")); // "habcdefabcdefg" "habcdefundefinedabcdefg"

could you help me, whats wrong with it. Thank you

4 Answers

You could try another approach and use the slice function

function reverseString(string) 
{
    if (string.length < 2) { return string; }

    let stringHalfLength = string.length / 2;
    let isLengthOdd = stringHalfLength % 1 !== 0;
    
    if (isLengthOdd) {
        return string.slice(Math.ceil(stringHalfLength), string.length + 1) + string[Math.floor(stringHalfLength)] + string.slice(0, Math.floor(stringHalfLength));
    }
    
    return string.slice(stringHalfLength, string.length + 1) + string.slice(0, stringHalfLength);
}

console.log(reverseString("aaabccc") === "cccbaaa"); 
console.log(reverseString("aab") === "baa"); 
console.log(reverseString("aaaacccc") === "ccccaaaa"); 
console.log(reverseString("abcdefghabcdef") === "habcdefabcdefg"); 

A more efficient way to reverse the string would be to split the string, then use the built-in reverse javascript function (which reverses the elements of the split string), and then re-join the elements using the join function.. No need to re-invent the wheel?

You can concatenate the functions in shorthand (.split.reverse.join etc...) so your function would look something like this:

function reverseString(string) {
    return string.split("").reverse().join("");
}

Try it out!

function reverseString(string) {
  return string.split("").reverse().join("");
}

console.log(reverseString("hello"));
console.log(reverseString("aaabbbccc"));

If there's a particular reason you're opting not to use the in-built functions (i.e. if I've missed something?) , feel free to comment.

The short version of what you need:

function reverseString(string) {
    const splitPosition = Math.ceil(string.length / 2);
    return string.substring(splitPosition) + string.substring(0, splitPosition);
}

The key to your question is the middle element. To accomplish that, you probably want to use Math.floor that round under.

console.log(reverseString("aaabccc")); // "cccbaaa" console.log(reverseString("abcdefghabcdef")); // "habcdefabcdefg"

function reverseString (str) {
    if (str.length<2) {
        return str
    }
    var half = Math.floor(str.length / 2);
    return (str.slice(-half) + (str.length%2?str[half]:"")  + str.slice(0,half));
}

reverseString('')
> ""

reverseString('1')
> "1"

reverseString('12')
> "21"

reverseString('123')
> "321"

reverseString('1234')
> "3412"

reverseString('12345')
> "45312"

reverseString("aaabccc")
> "cccbaaa"

reverseString("abcdefghabcdef")
> "habcdefabcdefg"

So basically your problem is not to grab 2 parts of the string and rearrange, it is to grab 3 parts.

  • 1 part: str.slice(0,half)
  • 2 part: str.length%2 ? str[half] : ""
  • 3 part: str.slice(-half)

The second part is empty if the string length is even and the middle character if is odd.

So the code version in long self explanatory code:

function reverseString (str) {
    if (str.length<2) {
        return str
    }

    var half = Math.floor(str.length / 2);

    var firstPart = str.slice(0,half);
    var midlePart = str.length % 2 ? str[half] : ""; // we could expand also this
    var endPart = str.slice(-half);

    return endPart + midlePart + firstPart;
 }

And also, notice the precondition, so I don't have to deal with the easy cases.

Also, in your code, you got undefined because you access in the last loop to: string[string.length] you need to change <= by <

Related