Using split to display string in UI

I have a string containing this value:

05/22/2023 46 hrs ago

I need to display it in UI like this:

enter image description here

Here is my code:

<div> {fieldContent.split(" ")[0]}</div>
<div> {fieldContent.split(" ")[1]}  {fieldContent.split(" ")[2]} {fieldContent.split(" ")[3]}</div>

which works fine. But, is there a different way to display this value instead of hardcoding 0, 1, 2, 3 using split?

>Solution :

This code snippet is just one of the numerous approaches available in JavaScript to solve this problem.

const str = "05/22/2023 46 hrs ago"
const spaceIndex = str.indexOf(" ");

// Split the string into two parts based on the first space
const firstPart = str.substring(0, spaceIndex);
const secondPart = str.substring(spaceIndex + 1);


More accurate way of separating date is:

const str = "05/22/2023 46 hrs ago";

// Extract the date and time parts using regex
const regexPattern = /^(\d{2}\/\d{2}\/\d{4})\s(.*)$/;
const [, datePart, timePart] = str.match(regexPattern);

// Output the date and time parts

Leave a Reply