- 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.
- Your bot responds to the users primarily in text and you want them to make it better.
- You want the big text responses to format in more than one line or paragraph.
- You can't remove the leading spaces properly of every line separated with a new line character.
- You can't remove extra spaces between messages which might be typed by the developer unknowingly.
- 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 ...
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