Formatting text responses better for Dialogflow Agent

If your bot is responding to the users primarily in the text then there may be a need to format those text messages in the following conditions. This is also applicable for any bot backed by JavaScript/Node.js codes.
  1. You have the following environmental conditions.
    • Node.js or Javascript.
    • Visual Studio Code or Similar IDE with auto code/document formatting options.
    • You have the text responses in the code itself.
    • You need to avoid long lines in the code.
    • The long text responses also need to be handled efficiently with the code.
    • You use new lines to handle long text responses.
  2. Your bot responds to the users primarily in text and you want them to make it better.
  3. You want the big text responses to format in more than one line or paragraph.
If you face the following problems in the above conditions then the following piece of code will give you an idea of how to solve this problem.
  1. You can't remove the leading spaces properly of every line separated with a new line character.
  2. You can't remove extra spaces between messages which might be typed by the developer unknowingly.
  3. You are struggling to make the bot responses look symmetrical when it involves multiple lines.
'use strict'

function formatMessage(message) {
    let lines
    const trimmedLines = []
    if (message) {
        lines = message.split('\n')
        lines.forEach(line => { // this will handle the each line of the message separately
            // replace(/\s+/g, ' ') will replace more than spaces to one space
            trimmedLines.push(line.trim().replace(/\s+/g, ' '))
        })
        message = trimmedLines.join('\n')
    }
    return message
}

module.exports = { formatMessage }
In general, this piece of code also gives you an idea of how to handle leading and trailing spaces in multiline strings. Also, it shows how to use a regular expression to remove spaces in a string.

Following is a usage of the above function -
'use strict'

const { formatMessage } = require('./string')

// your other codes go here ...

  agent.add(formatMessage(`Hi ${userIdentity.first_name_copy}, 
            your identity is pending to verify with ${userIdentity.email_id_copy}. 
            Please enter the four-digit OTP from that email here. 
            Or do you want to change your identity details? 
            (Tip: enter y instead of the OTP to change identity details)`))
            
// your other codes go here ...

            

1 comment:

  1. Thank you for the valuable post. Must be the developers are searching for this type of content across the internet but a few they get like this luckily. Please keep going...

    ReplyDelete