Strategies for reversing strings in JavaScript without relying on built-in functions

Are you wondering how to reverse the words in a string without using the split, reverse, and join functions?

Here is the problem: You need to reverse the words in a string. For example, if the input is "Hello World," the output should be "World Hello."

<script>
  var newString = ""; 
  var theString = prompt("Enter a Phrase that you would like to reverse (Ex. Hello world)"); 

  // Your code here

  document.write(newString);
</script>

Although you could easily achieve this using built-in methods, the challenge is to only use the following:

  • Arrays
  • Substring
  • charAt()

How would you approach this task?

Answer №1

Alright, here's a technique you can use if you have the ability to utilize the charAt function to detect spaces between words. By identifying the spaces, you can then employ the substring method to extract and store each word separately in variables. After that, you can manipulate them and concatenate them back together. Let me demonstrate with an example:

var string = "Hello World",
    words = [],
    reversedString="",
    i;

for (i=0; i<string.length; i++) {
  if (string.charAt(i) === " ") {
    words.push(string.substring(0, i));
    words.push(string.substring(i));
  }
}

for (i=words.length-1; i>=0; i--) {
  reversedString += words[i];
}

Keep in mind that this is just a straightforward (untested) illustration and is tailored for a two-word string. If you wish to expand this to handle more words, you'll need to adjust the substring logic accordingly. I hope this guidance proves beneficial!

EDIT: I just realized that I forgot to reverse the string at the end; I've updated the code.

If you require further information, here are a couple of resources for your reference: substring charAt

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Absence of property persists despite the use of null coalescing and optional chaining

Having some trouble with a piece of code that utilizes optional chaining and null coalescing. Despite this, I am confused as to why it is still flagging an error about the property not existing. See image below for more details: The error message display ...

Is it necessary for React components to be organized in a hierarchy?

In all my years, I've been told that React components should follow a tree hierarchy so that parent components can manage state and pass it down to their children. But is this truly necessary? The guiding principle of React states that "React has bee ...

What purpose does sending null to XMLHttpRequest.send serve?

Have you ever wondered why send is often called like this? xhr.send(null) instead of just xhr.send() ? W3, MDN, and MSDN all mention that the argument is optional. Additionally, the ActiveX control seems to work without it: hr=pIXMLHTTPRequest.Create ...

Angular5+ Error: Unable to retrieve summary for RouterOutlet directive due to illegal state

When attempting to build my Angular App using ng build --prod --aot, I consistently encounter the following error: ERROR in : Illegal state: Could not load the summary for directive RouterOutlet in C:/Path-To-Project/node_modules/@angular/Router/router.d. ...

Discovering intersection points along a line between the previous and current positions of the mouse in Three.js

I am working on a project in Three.js where I have a scene filled with lines. Everything is working smoothly when the mouse moves slowly, as I am using the raycaster method to check for intersections with the lines. However, the issue arises when the mouse ...

Calculate the sum of various column values within a complex multidimensional array featuring varying row structures

I'm dealing with a complex multidimensional array that goes up to 4 levels deep. Not all columns exist in the lower levels and some columns contain subsets instead of regular values. My goal is to calculate the total sum of certain column values. Sp ...

Utilize Chrome storage instead of localstorage to generate Parse sessions

I'm currently developing a Chrome Extension that relies on Parse User sessions. Because localstorage is limited to specific domains, I am looking to utilize chrome.storage so the data can be accessed across any site. The existing Parse Javascript SDK ...

Incorporating TypeScript basics into the if statement post compiling

As I delve into the Angular2 Quickstart, I stumbled upon a peculiar issue within app.component.js after compiling app.component.ts using tsc (version 1.8.2): if (d = decorators[i]) I am unable to pinpoint where I may have gone wrong in configuring the qu ...

AJAX issue: "Content-Type header is missing the multipart boundary parameter"

Currently, I am encountering an issue while attempting to transfer a file from localhost to a server. The error message displayed in my network console is as follows, with status code 500: "no multipart boundary param in Content-Type" To address this p ...

Using wildcard in Angular app for MQTT observation

My curiosity lies in MQTT wildcards and how they function, specifically while utilizing the mosqitto broker. Let's say I have around 1-2k topics. In my frontend, I am observing them with a single-level wildcard using ngx-mqtt. Will there be a separat ...

The directive call triggers the loading of data from MongoDB

I'm currently working on a small invoice demo application using Angular. The data is stored in a MongoDB and is called in a controller named invoiceCtrl. Here's how the controller looks: invCon.controller( 'invoiceCtrl', ['$http&a ...

The offcanvas close button fails to function if initialized through JavaScript

I have integrated offcanvas into the page layout. By default, it remains hidden but I want it to be visible at all times on large screens. On smaller screens, there should be a button to dismiss it, as well as another button in the menu panel to show the o ...

simulating interaction with databases within API routes

I am currently working on developing a full stack application using NextJS along with a MySQL database. Within my API routes, I interact with this database by making calls to various functions such as createOne(), which is responsible for creating new inst ...

Error on Network: 400 BAD REQUEST in Ionic framework

I recently implemented push notifications successfully, but I am facing a network error with a 400 bad request when trying to access a specific API endpoint. The error message states: "NetworkError: 400 BAD REQUEST - https://apps.ionic.io/api/v1/app/77c3 ...

Tips for combining data from various sources in GraphQL

Need some guidance on setting up GraphQL as a beginner. I am facing challenges in efficiently setting up resolvers for my schema, especially when dealing with fields from different backend APIs. type User { name: String address: String dateOfBirth ...

Stopping a parent's event from firing when clicking on child elements without interfering with the child element events

Having read several posts such as this one, I am exploring a method to click on the parent div for it to hide, without hiding when clicking on either the search box or the 'click for event 2' text. I have tried using onclick stop propagation to ...

Resolving label overlapping issue in Chart.js version 2

I am currently utilizing Chart.js 2 for a project of mine. I've successfully customized the style, but there's one persistent issue that I can't seem to resolve and it's becoming quite frustrating. Occasionally, the last label on the x ...

Assign a variable name to the ng-model using JavaScript

Is there a way to dynamically set the ng-model name using JavaScript? HTML <div ng-repeat="model in models"> <input ng-model="?"> </div JS $scope.models= [ {name: "modelOne"}, {name: "modelTwo"}, {name: "modelThree"} ]; Any ...

Loop through an array of items and use the preg_match_all function to find matches for each item

I am currently working on modifying Interspire Email code. The program is set up to analyze the HTML content of emails before sending them, specifically looking for 'a href' links to replace. However, I would like to expand this functionality to ...

How can I efficiently utilize HTML/CSS/JS to float items and create a grid that accommodates expandable items while minimizing wasted space?

After meticulously configuring a basic grid of divs using float, I've encountered an issue. When expanding an item in the right-hand column, the layout shifts awkwardly. My goal is to have boxes A and B seamlessly move up to fill the empty space, whi ...