Flip words that have over 4 characters

I need some assistance understanding why my function is consistently returning undefined.

The desired output involves reversing each word in a string that has more than 4 characters.

As a bit of a JavaScript beginner, this issue has been quite baffling for me! 😅

Your help is greatly appreciated!

const reverseString = (input) => {
    input = input.split(' '); //convert to array
    input = input.map(function(word){
        if (word.length > 4) {
            return word.split('').reverse().join('');
        } else {
            return word;
        }
    });
    return console.log(input.join(' '));
}

reverseString('Hello World thank you so much');

Answer â„–1

To begin with, the forEach method in JavaScript returns undefined, so you cannot directly assign values to the source array. If you want to reverse a string and assign it back to the source array, it's recommended to utilize the third parameter (source array) of the callback function in forEach.

Learn more about forEach

const reverseString = (data) => {
  data = data.split(" "); // convert to an array
  data.forEach(function flipper(x, i, src) {
    x = x.split("");
    if (x.length > 4) {
      x = x.reverse();
    }
    x = x.join("");
    src[i] = x;
  });
  return data.join(" ");
};

const result = reverseString("Hello World thank you so much");
console.log(result);

You can achieve the same functionality easily using map

const reverseString = (data) => {
  return data
    .split(" ")
    .map(x => x.length > 4 ? x.split("").reverse().join("") : x)
    .join(" ");
};

const result = reverseString("Hello World thank you so much");
console.log(result);

Answer â„–2

When looking at your code, you are setting the result of forEach() equal to the data variable.

It's important to note that forEach() doesn't return anything other than undefined

To learn more about forEach(), check out the MDN documentation

You might want to consider using the map function in the previous answer instead.

Answer â„–3

Here is an updated version of your function:

const modifyString =
    information => information
      .split(" ")
      .map(item => item.length > 4 ? data.split("").reverse().join("") : item)
      .join(" ");

Answer â„–4

Here's a different method using regular expressions within the replace() function and a callback for replacement

const reverseString = str => str.replace(/\S{5,}/gi, (s) => [...s].reverse().join(''))

const str ='Hello World thank you so much';
console.log(reverseString(str))

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

When information is provided, record the values in a separate input field

I'm struggling to come up with an appropriate title... Here's the issue: if a user inputs anything into the "Accompanying Person" field, the "Accompanying Person Price" field will automatically be set to 260€. I have no clue on how to achieve ...

Troubleshooting Problems with Loading Data into Highcharts using Javascript

The server is returning data in the following format: {"barData": [ {"Accepted":[0,0,0]}, {"Rejected":[0,0,0]}, {"In_Process":[0,1,0]}] } On the browser, it appears as follows: I initially thought that this was the correct st ...

What is the proper way to integrate three.js (a third-party library) into the view controller of an SAPUI5 application

Seeking a Solution Is there a way to integrate the three.js library into SAPUI5 in order to access it using THREE as the root variable in my main view controller? I attempted to create a directory named libs within my project folder and include it in the ...

Hey there, could you please set up the DateTimePicker in my expo project using React Native?

Hey everyone, I'm currently trying to set up DateTimePicker but encountered an error. Here's the issue: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: undefined@undefined npm ERR! Fou ...

Successfully transferring canvas image to server. Saving empty picture file

I have a piece of code that creates an image from an equation editor when the save button is clicked and displays it on a canvas. However, after displaying it, I am having trouble saving it as the saved image appears blank. Can someone please help me ident ...

Fixed-positioned elements

I'm facing a small issue with HTML5 that I can't seem to figure out. Currently, I have a header image followed by a menu div containing a nav element directly below it. My goal is to make the menu div stay fixed when scrolling down while keeping ...

Click on the designated button to initiate a new tab

My goal is to show the content of each button in a specific tab when I click one of the 5 buttons, using vue.js. As a beginner with Vue, I've been struggling with this for the past week. Can someone please assist me? Thank you. ...

The `toString` function is displaying an array instead of the expected string

As a beginner in programming, I am currently enrolled in an introductory JavaScript course. However, I am facing an issue with my assignment where the toString method is printing an array instead of a string. Despite thorough research, I have been unsucces ...

React - onchange event for input checkboxes does not trigger on the initial click

The behavior of a checkbox input is proving to be quite unreliable. Currently, I am setting the checkbox state based on the store's state, which generally works well. However, there are instances where checking the checkbox does not trigger the oncha ...

Key within square brackets in a JSON array

I am dealing with a JSON array that includes a square bracket in the key, like this: { "msg":"OK", "data":[ { "nls!type":"NCR", "current":"Assign", "physicalid":"0FFE0001000009FC5BD6805C00001352", "attribute[custTitle]":"Tit ...

Concentrate on elements that are activated without the need for clicking

Is it possible to trigger an action when an input is focused without the focus event being initiated by a click? $('#input').focus(function(){ if(not triggered by click) { alert('Hello!'); } }); ...

Implementing Blob image rendering in Vue.js from a database

In my front-end development, I am utilizing Vue.js. On the backend, I have set up Node.js, Express, and PostgreSQL with Sequelize. One of the challenges I encountered involved storing an item in the database that includes a thumbnail image. Database Model ...

The error message "Encountered an issue when trying to access properties of undefined (reading 'getState')" was

Currently working on developing an app that utilizes a Django backend and React frontend. The goal is to enable users to log in, receive refresh and access tokens from Django, store the token in local storage, and redirect authenticated users to a static p ...

Leveraging express functions in Node.js framework

Currently, I am delving into the world of nodeJS and have stumbled upon a great collection of tutorials. The tutorials are focused on teaching me about a powerful framework known as express. In order to utilize express effectively, one must also grasp the ...

Changing the Flash message to an Alert message in Symfony2: A step-by-step guide

I've encountered a problem where the success message from an action method in Symfony2 Controller appears as a flash message, but I need to display it as an alert or dialogue message according to requirements. I have attempted various solutions witho ...

The issue of the background image not updating with jQuery persists in Internet Explorer 11

Hello everyone, I am facing an issue where I am trying to change the background image of a div using jQuery on click. The code I have written works perfectly on all browsers except for IE. Can someone please provide me with some guidance or help on how to ...

Troubleshooting "These dependencies were not found:" error message during deployment on Netlify, despite successful execution of yarn run serve on local machine

Currently, as I am creating a website using Vue.js, yarn, and Netlify. The build process works smoothly on my local machine when running yanr run build. However, upon deploying it through Netlify, an issue arises: 5:17:55 PM: failed during stage 'bui ...

Tips for aligning the dialog box in the center of the screen based on the current scroll position

Is there a way to center the dialog box vertically at the current scroll position of the window when any of the "show dialog" buttons are clicked? For instance, if I click on location 3, I want the dialog box to be centered vertically within the current v ...

Anchoring HTTP headers in HTML tags

Currently, I am working on some code to enable dragging files from a web app to the desktop by utilizing Chrome's anchor element dragging support. The challenge I am facing is that certain file links require more than a simple GET request - they nece ...

now.js - There is no method in Object, however the click event works in jQuery

Here is a simple NowJS code snippet for the client side: $j(document).ready(function() { window.now = nowInitialize('http://xxx.yyy:6564'); now.recvMsg = function(message){ $j("body").append("<br>" + message); } $ ...