简体   繁体   中英

how to build a message string, using array values when present

I a trying to display a warning to the user, I split an array, and always use the 0 and 1 position values, sometimes the array might contain a value in position 2, not all the time.

I would like to build the message string to show the value of arr[2] if it's there, or only arr[0], and arr[1] if not arr[2] is present.

I tried to do it this manner:

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.';

Just by looking at it and seeing the redundancy, I know I am doing it wrong, or not best practice. But somehow it works, but only whne arr[2] has a value because the part in which I check for arr[2] length, if not there, then the code breaks.

Is it possible someone could show me how to correctly use the ternary operator to achieve this goal?

Thank you kindly, Erasmo.

const prefix = (arr.length > 2 ? arr[1] + arr[2] : arr[1]);
const strWarningMsg = `${prefix} 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\nPress Cancel to abort the operation.`;

Pull the prefix out and derive it based on the number of elements in the array. Also, if you change your string to be a string literal instead, you can have literal new lines in your string, rather than \\n and have it be much more readable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM