JS function to reverse a string

Not to worry, I've managed to figure out how to reverse a string (a one-word string at least).

> function reverse(s){
>     return s.split("").reverse().join(""); }

Is there a way to reverse a string in this manner:

"Dady come home" -> "ydaD emoc emoh"

or for example:

('double  spaced  words') === 'elbuod  decaps  sdrow');

I've spent a few hours today trying to solve this because I'm learning, any tips would be greatly appreciated! Thank you!

Kindly refrain from providing a full reply with code. :) I'm just looking for some helpful hints.

Answer №1

Divide the sentence into individual words at each space using word.split(' ')

After that, go through each word and reverse its order with x.split('').reverse().join(''); (which you've already figured out :D) I implemented this using .map() instead of a for loop, as it is cleaner -- you can learn more about the .map() method at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Once all the words have been reversed, combine them back into a string strArray.join(' '); using an empty space to reconnect them.

var str1 = "Hello";
var str2 = "Daddy come home";
var str3 = "double  spaced  words";

function reverseWords( word ){

  let output = '';
  
  // Split words based on spaces
  let subStrArray = word.split(' ');
  
  // Reverse each word
  let updatedStrArray = subStrArray.map( (x) => {
    let result = '';
    if( x ){
      result = x.split('').reverse().join('');
    }
    return result;
  });
  
  // Combine back into a string
  output = updatedStrArray.join(' ');
  
  console.log( output );
  
  return output;

}

let rev1 = reverseWords( str1 );
let rev2 = reverseWords( str2 );
let rev3 = reverseWords( str3 );

// Testing forward and backward transformation ...
reverseWords( rev1 );
reverseWords( rev2 );
reverseWords( rev3 );

Answer №2

To start, divide the string by spaces and then flip each word around

 string.split` `.map(a=>[...a].reverse().join``).join` `

var string = "Hello there";
console.log(string.split` `.map(a=>[...a].reverse().join``).join` `)

Answer №3

To separate the text into individual words, employ a regular expression that identifies consecutive spaces, such as /(\s+)/. Following this, you'll obtain an array of words and can apply either Array.prototype.map (or a loop) to invert each word one by one, then utilize Array.prototype.join to generate the ultimate outcome.

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

Is there someone who can assist me in transferring data from an Axios JSON response to plot points on a line chart using Chart js?

I'm currently in the process of developing a React application that includes a line chart showcasing the timeline of data recordings starting from a specific point in time up to the present day. To achieve this, I am leveraging the Chart.js JavaScript ...

Struggling to make jQuery code function in an external file without causing clashes with additional jQuery code

When incorporating this simple code into its own separate file, I encounter some jQuery conflicts with another piece of code. jQuery(function ($) { $(".tabContents").hide(); $(".tabContents:first").show(); $("#tabContainer ul li a").click(fun ...

Dynamic user group system that leverages Ajax technology for seamless integration with an HTML interface, powered by PHP and

I am new to this, so please forgive my lack of knowledge. Currently, I am in the process of creating an Ajax-driven web application for managing user contact groups. This application allows users to store contacts based on assigned groups. Once a user con ...

Firestore - Safely removing a large number of documents without running into concurrency problems

I've encountered issues with my scheduled cloud function for deleting rooms in a Firestore-based game that were either created 5 minutes ago and are not full, or have finished. Here's the code I'm using: async function deleteExpiredRooms() ...

PHP: display item from array based on its value rather than its array index

In my array, each item has two values - an "ID" and an "en". The ID values are unique integers while the en values are text. Now, I want to be able to echo a specific item from the array using its ID as reference. I attempted the code below but it retrie ...

Tips on saving a form submit button data to localStorage

As a newcomer, I am on a quest to make this function properly. My goal is to create a form where the submit button saves data to the localStorage. Here's what I have tried thus far. <script> function storeRecipe() { localStorage.setItem($(" ...

Double the Power of jQuery Live Search with Two Implementations on a Single Website

I recently implemented a JQuery Live Search feature that is working perfectly. Here is the JQuery script: <script type="text/javascript"> $(document).ready(function(){ $('.search-box input[type="text"]').on("keyup input", function(){ ...

Using TypeScript to Verify the Existence of Words in a String

Is there a way in typescript to find specific words within a given string? For example: If we have a list: ['Mr', 'Mrs', 'FM.', 'Sir'] and a string named 'Sir FM. Sam Manekshaw'. The words 'Sir' ...

Adding color between lines in Three.js

I have two different sets of vertices. One set contains real vertices, and the other set contains the same vertices but with a y value of zero. I am trying to connect these vertices and fill them in but have not been successful so far. I have attempted to ...

Heroku deployment failed: Push rejected due to lack of a Cedar-supported application

Trying to deploy my 3D game (created with three.js) on a Heroku server has brought up an issue. After running the command "git push heroku master," I encountered the following problem: Initializing repository, done. Counting objects: 252, done. Delta com ...

Step-by-step guide for implementing a scroll event on FancyBox

I am facing an issue with a large fancybox popup that contains a scroll function. I need to find a way to attach an event to this fancybox popup when scrolling. I have tried several different events, such as: $('.fancybox-inner').off("scrol ...

Why is it that my JQuery sliders appear perfectly fine when viewed locally, but fail to show up when accessed on

I'm facing an issue with two JQuery sliders on my page. The local version works fine, but when I upload it to my web host, only one slider functions correctly. I need both of them to work as intended. Any insights on how to resolve this problem? See ...

The functionality of Jquery appears to be malfunctioning on the Drupal platform, although it performs

I've built a jQuery carousel that is fully functional when tested locally, but encounters issues when uploaded to a Drupal platform. Surprisingly, the jQuery functions properly when entered through the Console. Here's the jQuery code: carousel = ...

Send an array from PHP to jQuery using AJAX, then send the array back from jQuery to PHP

I am facing a dilemma where I am passing an array from PHP to jQuery AJAX using `json_encode` and storing it in an empty array declared in the jQuery script as `var myarr = []`. Later in the same script, I am sending the same array `myarr` back to the PHP ...

Exponential calculator in Javascript

I'm working on a basic calculator project using html5, css3 and javascript. However, I've run into an issue with the exponent button not functioning properly. Here's my code snippet: <html> <head> <meta charset = "utf-8" ...

"Troubleshooting: Issues with Ajax's .load() function disrupting

I'm encountering a strange issue where the load() function is causing my carousel to malfunction. Within my Slick Slider, I have 3 slides. You can navigate to the next slide by clicking the NEXT button. Alternatively, clicking on the slide itself loa ...

Determine in Jquery if all the elements in array 2 are being utilized by array 1

Can anyone help me figure out why my array1 has a different length than array2? I've been searching for hours trying to find the mistake in my code. If it's not related to that, could someone kindly point out where I went wrong? function contr ...

Preventing a sprite from going beyond the boundaries of a canvas with pure JavaScript - here's how!

I am in the process of developing a game using native JavaScript, HTML, and a touch of CSS. I have two blocks called Sprites that tend to keep moving off the canvas edges when they reach them. Question: How can I utilize native JS to prevent the sprites fr ...

How can I designate a default value for a variable within a prop in a Vue.Js component?

I have a question regarding setting a default value for a prop using a getter. props: { userID: { type: String, default: '' } } The default value I want to set is obtained through: computed: { ...mapGetters('Auth&a ...

Custom Email Template for Inviting Msgraph Users

I'm currently exploring the possibility of creating an email template for the MS Graph API. I am inviting users to join my Azure platform, but the default email they receive is not very visually appealing. public async sendUserInvite(body: {email: < ...