Steps to substituting characters within a date string

Create a function called normalize that changes '-' to '/' in a given date string.

For example, normalize('20-05-2017') should output '20/05/2017'.

This is my attempt:

let d = new Date('27-11-2021');

function normalize(session){    
     let normal = d.replace('-','/');
     
     return (session);
}

Answer №1

When passing a string representation of a date to the normalize function, consider using the String.prototype.replaceAll() method to replace each instance of '-' with '/'. No need to parse the string as an actual Date object in this case.

// Create a normalize function that replaces '-' with '/' in a date string.
// Example: normalize('20-05-2017') should return '20/05/2017'.
function normalize(stringDate) {
  const normal = stringDate.replaceAll('-', '/');
  return normal;
}

const result = normalize('20-05-2017')
console.log(result)

Answer №2

Consider utilizing the replaceAll method in ES to improve efficiency over using the replace function.

let date = convertDateFormat('20-05-2017');
console.log('Updated date format: ',date);

function convertDateFormat(date){
    return (date.replaceAll('-','/'));
}

Answer №3

Initially, there seems to be an issue with the date format provided. When using the constructor, it is not possible to input 27-8-2021. To resolve this, consider following this approach.

let d = new Date();

d.toLocaleDateString() // outputs '8/27/2021'
d.toLocaleDateString('en-in') // outputs '27/8/2021'

Answer №4

function convertDate(input){    
    let newDate = input.replace('-','/');
    let updatedDate = newDate.replace('-','/');
    return updatedDate;
}

let dateInput = '27-11-2021';

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 a way to prevent the conversion of .json/.webmanifest URLs into base64 strings?

I've been grappling with an issue for quite some time now. In my VSCode vite-react-typescript project, I have a link in the index.html file pointing to a webmanifest, which is essentially a json file with a different extension. After building my app, ...

Change the local date and time to UTC in the format of yy:mm:dd H:M

I must change the date format from local time to UTC or ISO as yy:mm:dd H:M, or calculate the difference between local date times with 03:30 as yy:mm:dd H:M 2016-10-22T04:30:00.000Z convert this to 2016-10-22T01:00:00.000Z ...

Transferring data between various stages of the user interface

As a newcomer to angularJs, I find myself facing an issue with two forms existing in different UI states (URLs) labeled as Step 1 and Step 2. The process requires filling up Step 1 and moving to the next step by clicking the NEXT button, which then leads t ...

`What is the best way to employ the Return statement in programming?`

Trying to grasp the concepts of functions and methods has been a challenge for me. I often find myself confused about when, where, and how to use return statements in different situations. To illustrate this confusion, let's take a look at two code sn ...

Encountered a Next-Auth Error: Unable to fetch data, TypeError: fetch failed within

I've been struggling with a unique issue that I haven't found a solution for in any other forum. My Configuration NextJS: v13.0.3 NextAuth: v4.16.4 npm: v8.19.2 node: v18.12.1 When the Issue Arises This particular error only occurs in the pr ...

Comparing Jquery's smoothscroll feature with dynamic height implementation

Recently I launched my own website and incorporated a smoothscroll script. While everything seems to be working smoothly, I encountered an issue when trying to adjust the height of the header upon clicking on a menu item. My dilemma is as follows: It appe ...

Trigger an email notification in Google Sheets whenever a designated cell is populated

I am currently exploring ways to enhance collaboration in project management, especially when dealing with numerous stakeholders (Although there are free tools available, integrating new procedures into a public organization's projects can be quite ch ...

Upgrading React Native hot reloading leads to a complete reload of the application

Recently, I updated my React Native app from version 0.48 to 0.55. Unfortunately, after the upgrade, hot reloading stopped functioning. Any modifications to the files now trigger a complete reload of the app. I have attempted clearing all cache related to ...

Enhancing images by creating clickable sections in a more organized and efficient manner

Are there any other methods to make parts of an image clickable in a more organized way, aside from using the coordinates method or directly embedding images from Photoshop? <script> new el_teacher = ["candice","john"]; $(".teacher1").mouseenter(fu ...

Access a JSON response within an HTML/JavaScript document

Can the scenario below be achieved? Here is the ajax response I received: HTML <body> <input type="text"></input> <div id="trydiv"></div> </body> JS $.ajax({ type: "POST", url: "json.php", ...

ID is Enclosed in Quotation Marks by JSON.Stringify

My JSON file is being modified by using JSON.stringify and JSON.parse based on updates from an online database. While everything is functioning correctly, there is an issue where numbers are being converted to strings with quotes in the JSON file. For in ...

Having difficulty retrieving the specific Laravel validation error message through AJAX

In my Laravel project, the error message I am encountering is: {message: "The given data was invalid.", errors: {oData: ["validation.required"]}} errors: {oData: ["validation.required"]} message: "The given data was invalid." I am not trying to display ...

Leverage the power of AJAX to fetch and display controller action results on the current

this is my code of the view I've set up a dropdown menu with options that have values like /ControllerName/ActionName. Upon clicking one of the dropdown values, it redirects me to another page with the selected ControllerName and ActionName. However ...

Is there a way to automatically close a created div by clicking anywhere outside of it?

I'm facing an issue with a dynamically created div that I want to close by clicking outside of it. However, when I try to achieve this functionality, the div closes immediately as soon as it is opened. closediv(); } function closediv() { d ...

Angular's ng serve is experiencing issues with mark-compacts near the heap limit, leading to an unsuccessful allocation

Encountering an issue while running ng serve in my Angular project. However, ng build --prod seems to be working fine. <--- Last few GCs ---> [4916:00000276B1C57010] 588109 ms: Scavenge (reduce) 8180.7 (8204.3) -> 8180.6 (8205.1) MB, 3 ...

Tips for disabling autofocus on Mui Menu Items

Incorporating a search functionality within a custom Mui Select component where the user can input a city or country to filter down the options list. The current issue is that when a user types a letter that matches the first letter of an option, the opt ...

Implementing Node.js with browser cache and handling 304 responses

I am currently in the process of creating a single page application with a standard HTML layout as shown below: <html> <head> <title>...</title> <link rel="stylesheet" media="all" type="text/css" href="css/main.css"> ...

Retrieving checkbox list values using jQuery

I am working with a div that contains some checkboxes. I want to write code so that when a button is clicked, it will retrieve the names of all the checked checkboxes. Can you provide guidance on how to achieve this? <div id="MyDiv"> .... <td> ...

What could be causing the issue with saving form data to local storage in React?

I am facing an issue with the code I have written to store data in local storage. Sometimes it works fine, but other times it saves empty data or erases the previous data when the Chrome window is closed and reopened. Any idea what could be causing this in ...

What is the best way to include the existing query string value in the hyperlinks on my page?

My main coding objective is to simultaneously search multiple websites. To accomplish this, I want to create a query string containing the search terms (primarily for analytics purposes) using a form. By utilizing JavaScript, I am aiming to include the s ...