Skip to content

Reverse string in JavaScript | Using for loop and inbuilt methods examples

  • by

There are serval ways to do Reverse string in JavaScript. The most common ways are using Using for Loop and built-in Methods (split, array reverse, and join).

Reverse string in JavaScript Examples

HTML examples:

Using for Loop

Inside function created empty “newString” variable. In for loop add last item first position in the new string, till last char remain.

<script>
		function reverseString(str) {
			let newString = "";
			for (let i = str.length - 1; i >= 0; i--) {
				newString += str[i];
			}
			return newString;
		}
		const result = reverseString("Hello world");
		console.log(result);

</script>

Using built-in Methods

First, Use the split method to split a string into individual array elements. Then use the array reverse() method to reverse elements. In the last join into a single string using the join() method.

<!DOCTYPE HTML> 
<html> 

<body> 

	<script>
		
		function reverseString(str) {

			const arrayStrings = str.split("");

			const reverseArray = arrayStrings.reverse();

			const joinArray = reverseArray.join("");

			return joinArray;
		}

		const result = reverseString("Hello world");
		console.log(result);

	</script>
</body> 
</html>		

Output: The result will be the same for both examples because the input string is the same.

Reverse string in JavaScript example

Do comment if you have any doubts and suggestions on this JS string topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading