Tips for aligning text to the right with JavaScript

I have a function that contains a few words. I want to display them in a single column with right alignment, each word on a separate line. For instance, 'I will get everything I want' should be displayed as: see image here
I will get everything I want

Answer №1

To achieve this using pure JavaScript, you can utilize the String.prototype.padStart() method.

const alignWordsToTheRight = (text) => {
  const words = text.split(' ');
  const longestWord = words.reduce((a, b) => (a.length > b.length ? a : b));
  const padGivenWords = words.map(word => word.padStart(longestWord.length + 15));
  return padGivenWords.join('\n');
}

const alignedWords = alignWordsToTheRight("I will get everything I want");

console.log(alignedWords);

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

Looping through the json resulted in receiving a null value

When working with typescript/javascript, I encountered an issue while trying to fetch the 'statute' from a data object: {_id: "31ad2", x: 21.29, y: -157.81, law: "290-11",....} I attempted to assign data.law to a variable, but received a typeer ...

Error: Failed to parse the given color specification

My chrome extension is showing an error message: Unchecked runtime.lastError: The color specification could not be parsed. This error seems to be in the popup.html: 1 -> <! DOCTYPE html> line. Can anyone explain what this means and how to fix ...

Implementing a pull-to-refresh feature in React Native using Redux

I need to implement pull to refresh functionality, but I'm unsure of what to call from _Refresh(). My actions, constants, and reducers are stored on another page. How can I trigger the API again? Thank you in advance for your assistance. class Homewo ...

What is the best way to handle mixed parameter types in Spring MVC when sending data from AngularJS?

I am struggling to pass a json object and a string as parameters to my Java controller. Despite my efforts, I keep receiving url = "" in the controller. What could be causing this issue? Is there a solution to successfully passing these parameters? $ ...

What could be causing my website's screen resolution to not fit properly on mobile devices?

Initially, the resolution perfectly matched the width of mobile devices. However, after changing the background image, for some reason, the width no longer fits the device length precisely. I've tried resetting to a point where the resolution was fine ...

Steps to handle the change event of a p:inputText element

In my current setup, I am utilizing p:inputText and have the need to trigger a javascript function that will update the searchField in the backend bean. <p:inputText required="true" placeholder="#{cc.attrs.searchTip}" value="#{cc.attrs.queryProperty}" ...

Tips for detecting the creation of an iframe before executing any javascript code

Before executing some JavaScript, I am trying to wait for an iframe to be created. I have attempted several methods, but none seem to effectively wait for the iframe. The console error that keeps appearing is Uncaught (in promise) TypeError: Cannot read pr ...

How to implement a "callWhenReady" function in JavaScript

I am new to javascript and currently working on restructuring my prototype code. The current setup involves multiple levels of nested callbacks, making it difficult to read and manage. I am aiming for a cleaner approach similar to the following: GoogleMap ...

Having trouble with Socket.io and its io.emit() method refusing to work? If communication from server to client isn't going smoothly, you may need a solution for sending data from the server to

My latest project is a document converter program that utilizes LibreOffice to convert documents to PDF format. Here's my server running on localhost:3000 import express from "express"; import bodyParser from "body-parser"; import ...

The slides on SlickJS are initially loaded in a vertical alignment, but once the arrows are interacted with,

I've put together a demonstration that highlights the issue I'm facing. Upon visiting the contact section, you'll notice that all the slickJS slides are stacked vertically initially, but once you interact with them by clicking on the arrow o ...

Bluebird refuses to execute the then() function, despite the code that was functional before

I am in the process of constructing a node framework for my upcoming projects, with a focus on easy management. The framework already includes a configuration module. Recently, I implemented an error handler and made updates to the Config module to incorp ...

There appears to be an issue with the functionality of the Bootstrap toggle tab

Currently, I am facing a toggle issue and having trouble pinpointing the root cause as there are no errors appearing in the console. The problem involves two tabs that can be toggled between - "pay" and "method". Initially, the default tab displayed is "pa ...

Avoiding console errors when a REST call fails

After conducting some research, it appears that achieving this is not possible. Therefore, I decided to seek advice. My current task involves making a REST GET call to check for the existence of a folder. If the folder does not exist, I create a new one; ...

The Enigma of AngularJS Coding

Check out this code snippet. $scope.$watch('year', reloadData); $scope.$watch('month', reloadData); $scope.year = 2017; $scope.month = 1; var reloadData = function() { /* Refresh Data */ } var init = function() { $scope.year ...

Use the npm-search feature to show only the name and description columns in the search results

After running the command npm search packagename, I noticed that the results are shown in 6 columns: name, description, author, date, version, and keywords. Is there a way to customize npm-search so that it only displays the name and description columns? ...

Creating Positioning Magic with HTML Elements

Currently working on an ASP.NET web app that utilizes a Master, with just a GridView at the bottom and a DIV at the top for further development. The goal is to keep the top DIV or header fixed while scrolling, ensuring it remains in place at the top of th ...

Automatic capitalization feature for input fields implemented with AngularJS

I have integrated a directive into my input field to validate a license key against a server-side API. While this functionality works well, I also want the license key to automatically add hyphens and appear in capital letters. For example, when a user in ...

The Jquery AJAX call is sending the data twice

Why is my AJAX request uploading my form data twice into the database? Here's the code for the AJAX function: function uploadProjects() { let projectName = $('#projectName').val(); let description = $('#description').val(); ...

Encountering a Problem When Exporting a Class Using Require

I find myself struggling with a particular detail that eludes me. Despite exploring numerous suggested solutions found through Google, I am overwhelmed by the uncertainty of what actually works. Here is MyProject on Replit and the problematic class I&apos ...

Need help making switch buttons in react-native?

Using the library found at this link has been quite successful on my iPhone, but it does not display properly on Android. It appears as shown here. ...