What is the process for inserting specific characters between JavaScript date values?

In my JavaScript project, I am attempting to adjust the date format to a specific style.

The format I aim for is 29-Jan-2021.

Currently, with the code below, I can generate "29 Jan 2021":

var newDate = new Date('2021-01-29T12:18:48.6588096Z')

const options = {
  year: 'numeric',
  month: 'short',
  day: 'numeric',
};

console.log(newDate.toLocaleString('en-UK', options))

Could someone lend me a hand in adding - between the day, month, & year components of the date mentioned above?

Answer №1

If you have already found a string close to your answer, there are two methods you can use to reach the solution.

You can either opt for replaceAll() or replace(). Both methods will effectively resolve the issue.

let dateFormatted = "29 Jan 2021"
console.log(dateFormatted.replaceAll(" ","-")) // 29-Jan-2021
console.log(dateFormatted.replace(/ /g,"-")) // 29-Jan-2021

I recommend using replace() instead of replaceAll since some browsers may not support replaceAll(). Be sure to verify the support for replaceAll function.

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

What is the best way to detect an empty string in AngularJS?

When working with a form, I needed to ensure that a string is not empty. If the string is indeed empty, I wanted to set a default value. Otherwise, I wanted to pass the actual value. Below is the code snippet from the controller: $scope.addElem = functi ...

The absence of a base path in NestJs swagger configuration

Everything was running smoothly on my local machine. However, I encountered a problem after deploying the application. After deployment, /querybuilder gets added to the base URL. Therefore, http://localhost:80/helloworld turns into http://52.xxx.xxx.139/q ...

Keeping calculated values in the React state can cause issues

In an attempt to develop a component resembling a transferlist, I have simplified the process substantially for this particular issue. Consider the following example: the react-admin component receives two inputs - a subset of selected items record[source ...

Clicking on the icon reveals the current date

I need some help with the input field that displays the calendar date. Currently, I can only click on the input field to show the calendar date. What I actually want is for users to be able to click on a calendar icon to display the calendar date, which sh ...

Extracting Ajax data - iterating through each piece of information

I am facing an issue with my ajax code. I have a collection of checkboxes, where the goal is to insert the data from the selected checkboxes into the database. When I choose just one checkbox, the insertion works fine. However, if I select multiple checkb ...

Incorporating a swisstopo map from an external source into an Angular

I am looking to integrate a swisstopo map into my angular 8 app. As I am new to angular, I am unsure how to include this example in my component: I have tried adding the script link to my index.html file and it loads successfully. However, I am confused a ...

Values returned by XmlHttpRequest

When it comes to returning data from an XmlHttpRequest, there are several options to consider. Here's a breakdown: Plain HTML: The request can format the data and return it in a user-friendly way. Advantage: Easy for the calling page to consume ...

Having difficulty removing a specific item from Firebase Realtime Database in React Native

I am currently working on developing a mobile app that allows users to create teams and players and save them into a database. While I have successfully implemented the team creation functionality, I am facing challenges with the deletion of individual pla ...

I am encountering an issue where I am unable to successfully fetch a cookie from the Express backend to the React

const express = require("express"); // const storiesRouter = require("./routes/storiesRouter") // const postsRouter = require("./routes/postsRouter"); // const usersRouter = require("./routes/usersRouter"); const cors = require("cors"); const cookieParser ...

What is the best way to update the value of a preact signal from a different component?

export const clicked = signal(false); const handleClickDay = (date) => { const day = date.getDate().toString().padStart(2,'0') const month = (date.getMonth()+1).toString().padStart(2,'0') const year = da ...

The preventDefault() function is not functioning properly on the <a> tag

As a JavaScript beginner, I decided to create an accordion menu using JavaScript. Although I was successful in implementing it, I encountered a bug in my program. In this scenario, uppercase letters represent first-level menus while lowercase letters repr ...

How can I properly parse a JSON file in Node.js?

Utilizing node.js, I have created a webpage (index.html) for visualizing a network graph using the vis.js library. To draw a network graph with this library, it is necessary to provide json arrays for both nodes and edges (see example). // array of nodes ...

Is it possible to embed HTML code within JavaScript strings?

Is my approach to inserting HTML into a JavaScript string correct? In particular, I want to insert an HTML link into a div tag using JavaScript. Here is the HTML: <div id="mydivtag"></div> And here is the JavaScript code: document.g ...

Adding labels to a JavaScript chart can be done by using the appropriate methods

https://i.stack.imgur.com/uEgZg.png https://i.stack.imgur.com/y6Jg2.png Hey there! I recently created a chart using the Victory.js framework (check out image 1) and now I'm looking to incorporate labels similar to the ones shown in the second image ab ...

Transferring attributes from grandchildren to their ancestor

My React.js application structure looks like this: <App /> <BreadcrumbList> <BreadcrumbItem /> <BreadcrumbList/> <App /> The issue I am facing is that when I click on <BreadcrumbItem />, I want to be able to ch ...

Problem with jQueryUI Sortable cancel property preventing input editing

Currently, I am utilizing jquery-3.2.1.min.js and jquery-ui.min.js version 1.12.1 The task at hand is to create a sortable list where certain elements are not sortable (specifically, other sortable lists). It is crucial that the input elements remain edit ...

What are some solutions for resolving a background image that fails to load?

HTML: `<div class="food-imagesM imagecontainer"> <!--Page info decoration etc.--> </div>` CSS: `.food-imagesM.imagecontainer{ background-image: url("/Images/Caribbean-food-Menu.jpg"); background-repeat: no-repeat; backgroun ...

What could be the reason for the ineffective custom error handling in mongoose?

In an attempt to improve the readability of error messages before they are displayed on the frontend, I am working on handling the required validation error as shown below: UserSchema .post('save', function (error, doc, next) { console.log ...

Is there a way to make the header reach the full width of the page?

Is there a way to make my header extend across the entire page? I attempted using margin-left and right, but it didn't yield the desired outcome. Header.css .header{ background: green; height: 70px; width: 100%; display: flex; ju ...

Tips for preventing the browser from freezing when incorporating a large HTML chunk retrieved through AJAX requests

I've developed a web application that showcases information about various items. Initially, only a small portion of the items are displayed at the top level. Upon loading the page for the first time and displaying these initial items, I make an AJAX r ...