When I try to reverse the words in a string, I am not receiving the desired order

Currently delving into TypeScript, I have set myself the task of crafting a function that takes in a string parameter and reverses each word within the string.

Here is what I aim to achieve with my output:

"This is an example!" ==> "sihT si na !elpmaxe"

The solution I've concocted involves steering clear of built-in methods.

export function reverseWords(str: string): string {
  var newStr = "";
  str.split("");
  for(var i = str.length -1; i >= 0; i--){
    newStr += str[i];
  }
  return newStr;
}

reverseWords("Hi. How are you?")

However, this code yields the following result:

 "This is an example!" ==> !elpmaxe na si sihT

What I am actually striving for is:

 "This is an example!" ==> "sihT si na !elpmaxe"

If anyone could shed some light on where I may be going awry, it would be greatly appreciated.

Answer №1

While your function is effective, it currently reverses the entire string instead of just the words within it. To address this, consider incorporating an additional function that utilizes your existing function to specifically reverse individual words:

export function reverseStringWords(str: string): string {
    var words = str.split(" ");
    var revWords = words.map(function(word){
        return reverseWords(word);    
    });
    return revWords.join(" ");
}

To enhance clarity and coherence within the code, you might want to rename your function as reverseWord. This adjustment will offer a more intuitive label in the given context.

Answer №2

If you don't wish to reverse the entire string, but instead reverse each word within the string while maintaining their relative positions, you can achieve this by first splitting the string by spaces and then reversing each substring:

const reverse = str => str
  .split(' ')
  .map(word => [...word].reverse().join(''))
  .join(' ');
console.log(reverse("This is an example!"));

Alternatively, if you prefer a manual approach, assuming that the use of split is acceptable:

const reverse = str => {
  const words = str.split(' ');
  const outWords = [];
  for (const word of words) {
    let letter = '';
    for (let i = word.length - 1; i >= 0; i--) {
      letter += word[i];
    }
    outWords.push(letter);
  }
  return outWords.join(' ');
};
console.log(reverse("This is an example!"));

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

The system is unable to locate a supporting entity with the identifier '[object Object]', as it is classified as an 'object'

I'm currently working on an Angular 2 application where I am retrieving data from an API and receiving JSON in the following format. { "makes": null, "models": null, "trims": null, "years": null, "assetTypes": { "2": "Auto ...

Unsure about the approach to handle this PHP/JSON object in Javascript/jQuery

From my understanding, I have generated a JSON object using PHP's json_encode function and displayed it using echo. As a result, I can directly access this object in JavaScript as an object. Here is an example: .done(function(response) { var ...

When displaying a collection of components, clicking a button will always select the most recent element in the array

Can you explain why this code won't work in a React environment? Every time the button is clicked, it picks up the value "name" from the last element in the array. In this example, the dialog will always display the name "John2". import React from "r ...

Troubles encountered with example code: Nested class in an exported class - Integrating Auth0 with React and Node.js

I am currently attempting to execute tutorial code in order to create an authentication server within my React project. Below is the code snippet provided for me to run: // src/Auth/Auth.js const auth0 = require('auth0-js'); class Auth { co ...

The Jquery append function is limited to the initial ajax request, necessitating a page refresh in order to populate another div with the desired

When making an AJAX request to retrieve a JSON array, upon successful completion another AJAX request is triggered. The retrieved data is then populated into the div of a bootstrap modal using the jQuery append function. Everything functions as expected ...

Implementing real-time streaming communication between server and client with Node.js Express

When a post request is made, the server generates data every few seconds, ranging from 1000 to 10000 entries. Currently, I am saving this data into a CSV file using createWriteStream and it works well. How can I pass this real-time (Name and Age) data to t ...

The function client.guilds.find cannot be located

Hey there! I've been tasked with working on a Discord bot that requires several dependencies to function properly. I've installed the necessary dependencies and attempted to run the bot using 'forever -o out.log bot.js'. However, I enc ...

Trouble with basic JavaScript functionality in a React component

Here is a unique component code snippet: import React, {Component} from 'react'; import 'D:/School/Alta/interactiveweb/src/webapp/src/App.css' class Chat extends Component { test() { alert(); } render() { return <nav ...

Moving the Promise.all feature from AngularJs to VueJs

I'm currently facing a challenge with moving a function from AngularJs to VueJs. I would really appreciate any help or suggestions you may have! items = { one: {...details here...}, two: {}, } In AngularJs: var promises = []; var deferred = $ ...

Bootstrap5: Left-aligned Navigation Bar Pills and Right-aligned Text

I am trying to align all my navigation pills to the left, and then add a single text element that stays at the end of the navbar even when the page is resized. Navbar Image My attempt involved adding a div so that the navbar pills would take up 50% width ...

Protractor unable to locate elements using by.repeater

What is the best method for targeting this repeater with Protractor? <a ng-repeat="item in filteredItems = (items | filter:'abc')">{{item}}</a> ...

Can VueJS support multiple v-slots in a component?

I recently set up vee-validate v3.0 for validation in my project and everything was going smoothly until I tried to style my elements. Despite following the documentation on styling and making changes to the vee-validate config, I encountered a new issue - ...

What is the procedure for renaming an item within a basic array in Angular?

I am working on a project in Angular and have constructed an array. I am now looking to change the name of one of the items in this array. While I have figured out how to rename keys in an array, I'm still unsure about how to do so for its values. ...

Stencil - React Integration Does Not Support Global CSS Styling

As per the guidance provided in the Stencil docshere, I have established some global CSS variables within src/global/variables.css. This file is currently the sole CSS resource in this particular directory. Upon attempting to incorporate my components int ...

Is it possible for a popup to appear without any user interaction

Do you ever wonder how certain websites are able to trigger pop-ups without being blocked by Chrome's pop-up blocker? I had always thought that pop-up blockers only allowed window.open if it was initiated by a user action. However, the situation seem ...

Conflicting Transformation Properties Causing CSS Issues Within a Single Element

I'm currently working on a user interface where users can drag and drop a box with a red outline to position it on the screen within a black box. See the UI here Alternatively, users can also move the box by adjusting the inputs on the right side. ...

Concealing alert messages automatically in CodeIgniter PHP after a certain amount of time

After attempting to use a script to hide the flash message once displayed, I found that it was not working as expected. The flash message remains visible until the page is refreshed. Controller: if ($this->email->send()) { $this- ...

Fetch data dynamically upon scrolling using an AJAX request

Instead of making an ajax call to load data, I want to do it on scroll. Here is the code I have: $.ajax({ type: 'GET', url: url, data: { get_param: 'value' }, dataType: ' ...

Next.js is throwing a TypeError because it does not recognize the function fs.readFileSync

In my JSON data file called total.json, I store information for a chatbot. { "guilds": 3, "users": 21 } Within my index.tsx file, I want to display this data on the webpage, so I attempt the following: import fs from 'fs'; f ...

Steps for creating a click event for text within an Ag-Grid cell

Is there a way to open a component when the user clicks on the text of a specific cell, like the Name column in this case? I've tried various Ag-Grid methods but couldn't find any that allow for a cell text click event. I know there is a method f ...