Guide on creating a message string by incorporating array values where available

I'm trying to show a warning to the user. I have an array that I split, and I always use the values in positions 0 and 1. Occasionally, there might be a value in position 2, but not always.

I want to create a message string that displays the value of arr[2] if it exists, or just arr[0] and arr[1] if arr[2] is not present.

I attempted to do it like this:

strWarningMsg =

    arr[2].length > 0 ? arr[1] + arr[2] + ' meeting, ' + '\nscheduled for: ' + arr[0].replace(/ +/g, " ")
    + '; data has been already uploaded.\n' + '\n Changes to the existing data could potentially invalidate any existing registration(s). Make sure to use the Cross-Reference file template before you attempt a new upload for this meeting.'
    + '\n\nPress OK to overwrite the existing Cross Reference List, or\nPress Cancel to abort the operation.'
   : arr[1] + ' meeting, ' + '\nscheduled for: ' + arr[0].replace(/ +/g, " ")
    + '; data has been already uploaded.\n' + '\n Changes to the existing data could potentially invalidate any existing registration(s). Make sure to use the Cross-Reference file template before you attempt a new upload for this meeting.'
    + '\n\nPress OK to overwrite the existing Cross Reference List, or\nPress Cancel to abort the operation.';

While I can see the redundancy in the code, I know it's not the best practice. It seems to work fine when arr[2] has a value, but it breaks when arr[2] is not there. Can someone show me the correct way to use the ternary operator to get this right?

Thanks, Erasmo.

Answer №1

const extractPrefix = (arr.length > 2 ? arr[1] + arr[2] : arr[1]);
const warningMessage = `${extractPrefix} meeting,
scheduled for: ${arr[0].replace(/ +/g, " ")}; data has been already uploaded.

Changes to the existing data could potentially invalidate any existing registration(s). Make sure to use the Cross-Reference file template before you attempt a new upload for this meeting.

Press OK to overwrite the existing Cross Reference List, or
Press Cancel to abort the operation.`;

Retrieve the prefix based on the array length. Convert the string to a string literal for better readability with literal new lines.

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

"PHP error: Accessing an undefined offset index 2

I'm currently working on a code snippet where I need to iterate through an array and replace specific characters within the 'color_codes' values. While the code is functioning correctly, I'm encountering an error message stating undefin ...

Adding a placeholder to a MUI Select component with different value prop and MenuItem options: a step-by-step guide

Is there a way to include a placeholder (-- Select --) in the MUI Select component below? const [country, setCountry] = useState("") <FormControl fullWidth error={!country}> <Select displayEmpty renderValue={selected => sel ...

Issues have been identified with React Native UI components RCTBubblingEventBlock and RCTDirectEventBlock not functioning as expected

In my custom native view within an Ignite project, I am facing a challenge with setting up communication from Objective-C to React Native. While the communication from React Native to iOS works using HTML injection, the reverse direction is not functioning ...

Showing the user's current location on a MapView in React Native

I'm having trouble setting the initial location of a MapView in my React Native app to the device's geolocation. Currently, I'm using a ref to update the coordinates with the help of the geolocation package. However, I'm facing an issu ...

Converting JSON data to an array using an Ajax request

I am currently working on an HTML project where I have the following code: <div id="main"> <div id="blogcont"> <p></p> </div> <button class="nvgt" id="prev" >Previous</button> <button ...

What is the best way to extract words from a string with spaces in C++?

Looking for a way to separate a string in C++? Let's say you have a string like this: aaa bbb Notice that there is a space before the second part of the string. Your aim is to extract only the first part - 'aaa'. Any text after the space s ...

Getting duplicate tokens for multiple users while utilizing Firebase messaging

When attempting to acquire a token from firebase, I employ the code snippet provided below: const messaging = firebase.messaging(); messaging.requestPermission() .then(() =>{ return firebase.messaging().getToken(); }).then(token => { s ...

Using React: Implementing conditional checks within the render() method of functional Components

When working with my usual React class Components, I typically perform some checks within the render() method before returning conditional html rendering. However, when using a react functional component, I noticed that there is no render() method availabl ...

Using Angular's filter pipe to search within a nested array

We are attempting to implement an angular pipe for filtering a list of sub-items, with the goal of removing parent items if there are no child items present. Here is the HTML code snippet we are using: <div class="row border-bottom item" *n ...

How do I use props to enable and conceal elements like lists, buttons, and images?

Check out this unique component: <ReusedHeader H1headerGray="text here... " H2headerRed="text2 here ! " pheader="p1" getStarted="button text1" hrefab="button url 1" whatWeDo="button text ...

Countdown Clock for Displaying Parsing Time in C#

On my aspx page, I have a submit button that triggers the parsing of ".txt" files when clicked. The parsing process generates results stored in tables and then redirects the user to another page. However, the issue at hand is that the parsing operation t ...

"Exploring the intricacies of routing within a Node.js application

I previously had around 100 blogs displayed on the "/" page with links for sorting by date (a-z). When clicking on these links, I am redirected to different routes - one is "/sort_by_date" and the other is "/sort_alphabetically". Unfortunately, I was unabl ...

Issue with retrieving attributes in the directive

One of the challenges I encountered is incorporating a directive that wraps the jQuery FullCalendar plugin into my project. Here is how I implement the directive: <div sg-calendar format-column-header-month='dddd' format-co ...

Discover the location by determining the distance from established points

Before I get redirected to this particular question, let me clarify that while I've come across it, I am unable to comprehend its content (I wish I could). What I'm really seeking is a straightforward method (bearing in mind my limited math skill ...

Assign an attendee the role of organizer in the Google Calendar API

I am currently utilizing the googleapis npm package to facilitate calendar event creation. Below is my request payload for calendar.events.insert in order to generate an event: { "summary":"Biology class", "location":"Google Meet: Please follow the go ...

Error code 2769 in Typescript occurs when attempting to transfer process information to the data state in order to utilize it within a modal

I'm encountering an issue while trying to pass a process to a setData state from a .map function in order to display it on a modal. The error message I'm receiving is: "No overload matches this call. Overload 1 of 2, '(props: { compone ...

Experimenting with a function invoked from a jQuery AJAX callback using Jasmine testing framework

Currently, I'm working on a function that utilizes an AJAX call to interact with a service. My main goal is to ensure the displayError function is triggered in case of a failure. The ajaxCall function is set up to accept a URL parameter. When the req ...

Building a Mongoose Schema with an Array of Object IDs: A Step-by-Step Guide

I created a user schema using mongoose: var userSchema = mongoose.Schema({ email: { type: String, required: true, unique: true}, password: { type: String, required: true}, name: { first: { type: String, required: true, trim ...

Enhancing Functional Components with Idle Timeout using React Hooks

I am currently working on an application that requires implementing an idle timeout feature. This feature should first notify the user that they will be logged out in one minute, and then proceed to log them out after the time has expired. Previously, I s ...

The luminosity of MeshBasicMaterial in Three.js

In my current setup with threejs, I am utilizing MeshBasicMaterial for lighting effects. Each element contains a simulated point light within. I have assigned a variable named color, defined as rgb(random value, random value, random value). I am looking ...