Reverse String without Built-in Methods

JavaScript

Reverses a string without using built-in methods:

You can reverse a string in JavaScript without using built-in methods like 'reverse()' by iterating through the string characters and constructing a new string in reverse order. Here's how you can do it:

js Copy Code
function reverseString(str) {
  let reversed = '';
  for (let i = str.length - 1; i >= 0; i--) {
    reversed += str[i];
  }
  return reversed;
}

// Example usage:
const originalString = "Hello, world!";
const reversedString = reverseString(originalString);
console.log(reversedString); // Output: "!dlrow ,olleH"
Output:
!dlrow ,olleH

Explanation:

1. Declare 'reversed' is initialized as an empty string.

2. We iterate through the original string from the last character to the first character.

3. In each iteration, we append the current character to the 'reversed' string.

4. Finally, we return the reversed string.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.