Anticipated a false result when comparing an empty string in JavaScript

Struggling with the CodeWars challenge The Hashtag Generator :

The marketing team needs help creating hashtags fast.
Let's simplify things with our own Hashtag Generator!

Here's what we need:

  • It should begin with a hashtag (#).
  • All words should be capitalized.
  • If the final result exceeds 140 characters, return false.
  • If either the input or output is empty, return false.

Examples

" Hello there thanks for trying my Kata"  =>  "#HelloThereThanksForTryingMyKata"
"    Hello     World   "                  =>  "#HelloWorld"
""                                        =>  false

This is my solution:

function generateHashtag (str) {
   if (str == "") {return false;}
   else
     {
      let text = str.trim();
      const myArray = text.split(" ");
      let word ="";
      let finalResult = ""
      for(let i=0; i< myArray.length; i++)
        {
          word = myArray[i];
          word = word.charAt(0).toUpperCase() + word.slice(1);
          finalResult =finalResult + word;
        }
      if(finalResult.length >140){return false;}
      else {return "#"+finalResult;}
    }
}

This is the error message I encountered:

Expected an empty string to return false: expected '#' to equal false

I'm puzzled by this error, as I have covered the check for an empty string in my code.

Answer №1

Two issues need to be addressed:

  • If the input contains only spaces, the result will still be an empty string. It is important to trim the input first before checking for emptiness.

  • The length test for the result is incorrect as it's done before adding the "#" symbol. The correct approach is to check if the length is greater than or equal to 140 after adding "#".

Here is the corrected code addressing these two issues:

function generateHashtag (str) {
   let text = str.trim(); // Trim the input first
   if (text == "") {return false;}
   else
     {
      const myArray = text.split(" ");
      let mot ="";
      let finalStr = ""
      for(let i=0; i< myArray.length; i++)
        {
          mot = myArray[i];
          mot = mot.charAt(0).toUpperCase() + mot.slice(1);
          finalStr =finalStr + mot;
        }
      if(finalStr.length >= 140){return false;} // Check length considering "#"
      else {return "#"+finalStr;}
    }
}

Alternatively, a solution using regular expression to extract words and "map" with "join" can achieve the same result more efficiently:

function generateHashtag (str) {
    const result = (str.trim().match(/\S+/g) ?? []).map(word =>
        word[0].toUpperCase() + word.slice(1)
    ).join("");
    return !!result && result.length < 140 && "#" + result;
}

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

Endless surfing just like Bing

I'm on the lookout for a library that can enable continuous scrolling in jQuery and/or JSP, similar to the functionality seen in Bing Images. Specifically, I want the feature where only the results within the visible area are loaded when users scroll ...

Running PHP code within a JavaScript application

I am looking to create an app that can control the volume of my LG Smart TV. While exploring possibilities, I came across this repository. After delving deeper into PHP, I have configured my PC (the only place where I plan to use the app) with WAMP Server. ...

Retrieve the width and height of an image

Does anyone know how to retrieve the dimensions of an image using JavaScript or jQuery when no styles are defined for it (resulting in jQuery's css() returning 0)? I suspect that the issue may arise from loading the image with jQuery right before att ...

Prevent index.html from being cached in the service worker in create-react-app

I am encountering an issue with my reactJs app that utilizes create-react-app. Despite updating the website or deploying a new build, Google Chrome always retrieves index.html from the service worker without making a network call. I suspect that caching o ...

Adding additional functionalities to ng-blur within the controller: A step-by-step guide

I am seeking to enhance the functionality of ng-blur for all input and textarea fields by adding a new function. These elements already have an existing ng-blur defined in the HTML, and my goal is to incorporate a new function into this existing setup from ...

What is the best way to retrieve the values of checkboxes in the order in which they are selected on a jsp page?

On my JSP page, I have implemented four checkboxes. I am looking to retrieve their values in the order they are selected. For example, if the checkboxes have values A, B, C, and D, and I select them in the order of B, D, A, and finally C, I want to captu ...

Guide on creating 2 select inputs with distinct elements?

Imagine you have two select inputs called 'Favorite Fruits' and 'Least Favorite Fruits'. Both of them contain a list of 5 fruits. // The following code is an example to demonstrate the issue <select name='favoriteFruits'& ...

When attempting to log an AJAX/JSON request, the console.log statement is displaying 'undefined'

Being new to AJAX, I have encountered an issue that I believe others may have faced as well. Despite numerous attempts and extensive research, I am unable to find a solution to this error. I am confident that it is something simple. Any help would be gre ...

An unexpected error occurred while attempting to retrieve data from Firebase and display it in another component

An error occurred: Unhandled Runtime Error Error: Element type is invalid - expected a string (for built-in components) or a class/function (for composite components) but got undefined. This could be due to forgetting to export your component from the defi ...

I'm facing some uncertainties with a couple of AngularJS code snippets

At my workplace, I am tasked with making modifications to an angularjs project. However, I find the code quite complex and challenging to fully comprehend: app.controller("complementsController", function($scope, $rootScope, $mdSidenav, $timeout, $localSt ...

Progress Bar Has Wandered Off Track

Having trouble with two queries. Take a look at the live view here First Query: Struggling to position the progress bar below my image using CSS. Second Query: Want to make the images slide left instead of fading with the progress bar in my Javascript. ...

JavaScript - Combining Elements in an Array

I am in the process of identifying unique records based on their ID and including the corresponding names with the following code. By replacing the if statement with: if (p.indexOf(c.ID) < 0) p.push(c.ID); This will generate an array with unique IDs, ...

What is the reason that the for loop updates all indexes in Node.js?

Currently, I am working on a space battle program that involves nested arrays. In order to simulate fleet fighting, I have written the following code: //Roll a dice function const randomNumber = (number) => { return Math.floor(Math.random() * numbe ...

Does angular have a feature comparable to JavaScript's .querySelectorAll()?

I developed an inventory calculator in JavaScript that provides item count based on weight. The calculator has 4 inputs, and now I'm looking to replicate the same functionality using Angular. Is there a method in Angular similar to .querySelectorAll() ...

What is the best way to incorporate gl-matrix into a ReactJS application?

Recently, I dabbled in using ReactJS and decided to experiment with this project that involves importing JS modules like this: import Particle from './Particle' I wanted to switch the project to use gl-matrix for practice with the framework, bu ...

How can I access an object from a JavaScript file within a Laravel blade template?

I am trying to implement the package Sortablejs in my blade file. After installing it with npm, I created a sortable.js file within my assets folder containing the following code: import Sortable from "sortablejs"; This file is compiled into th ...

Transferring data between functional components in ReactJS and dealing with the output of [object Object] or undefined

I'm struggling with passing a prop in functional components that are both located in the same .js file. I previously attempted to seek help for this issue, but unfortunately, it wasn't productive. My goal is to extract the member_id from the GET ...

The function is failing to provide a return value

In the Game.js file, there is a function that I am working on Game.prototype.onClick = function(event){ var x = event.x; var y = event.y; if (this.blueDeck[0].contains(x, y)) alert("Blue Deck Clicked"); } The OnClick function is ca ...

What is the method to retrieve a chat that has been ended with JavaScript SDK?

Whenever I attempt to retrieve a closed Twilio Conversation on the frontend using the JS SDK, I encounter a "Not found" error. Can closed conversations be fetched? My objective is to enable users to close a conversation while still having access to the m ...

Tips for transferring the button ID value to a GET request?

I recently developed a Node.js application that interacts with a database containing student information and their current marks. Utilizing MongoDB, I retrieve the data and present it in a table within an .ejs file. index.js router.get("/dashboard", funct ...