Add a new line whenever the API response includes the character '\n'

I'm currently working on a front end task that involves displaying API responses on the UI. The challenge I'm facing is that my API response contains messages with '\n' characters. Whenever '\n' appears, I want to create a new line so that any data following '\n' in the APIs is displayed on a separate line.

Here is the format of the response I receive from my REST API:

    {"errors":[{"code":"rm.config.unableToSet",
"innerError":"memoery xyz has no labels\nResource abc is in use and cannot be removed",
"logref":"c8a6f244-188e-4512-85c1-88788","message":"\"Unable to set data to DB\""}]}

Attached is a screenshot for reference.

https://i.sstatic.net/f59fOUI6.png

The issue lies in the 'innerError' field where '\n' is present. This message is intended to be displayed on the UI in a popup.

I've attempted the following methods:

1. innerError = innerError.replace(/\n/g, "<br>")

After applying the above method, the data displays correctly on the console. However, it fails to render properly on the UI.

2. I initially replaced '\n' with <br>, then reverted it back to '\n'.

As shown in the screenshot, the data is retrieved but doesn't appear on a new line as expected.

If anyone can suggest a solution to meet this requirement, I would greatly appreciate it.

Thank you in advance!

Answer №1

To make use of the CSS property white-space: pre-line, you can apply it to the specific element. This will cause the content to collapse when reaching the container's boundary and insert a line break at every newline character. Check out the demonstration below:

const textContent = 'The code snippet will display\nline breaks as intended';
document.getElementById('my-element').innerHTML = textContent;
#my-element {
  white-space: pre-line;
}
<span id="my-element"></span>

Answer №2

Does this meet your requirements? (Make sure to replace any instances of \n with \\n prior to parsing the JSON string and ensure that your JSON is properly formatted)

    let jsonData='{"errors":[{"code":"internal.error","details":"memory loss xyz occurred\nResource abc is currently in use and cannot be deleted","logref":"c8a6f244-188e-4512-85c1-88788","message":"\Error encountered while updating database\"}]}'
    
    jsonData = jsonData.replace(/\n/g,'\\n')

    const dataObj = JSON.parse(jsonData);

    alert(dataObj.errors[0].details);

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

Can a HTML id be assigned as a JSON object and then transferred to a different function?

My main goal is to send a JSON object to another function when a specific event occurs, such as a click event being triggered. $(document).on('click', '.some_link', function() { var something = "something"; $.get('/someDirect ...

I'm experiencing an issue with this code where it is returning the URL instead of the expected data

const http = require('http'); const xml2js = require('xml2js'); const parser = xml2js.Parser({ explicitArray: false }); const goodreadsService = function () { const getBookById = function (id, cb) { const options = { ...

Executing a function after Angular 2 Component is initialized

I am facing an issue. I am looking for a global service and I came across this helpful resource: Link. Although it works, I am now interested in having an event triggered after my component has been initialized and bootstrapped. Does anyone know of such a ...

How can you determine in Chrome when the content of an iframe has been modified by using document.write?

When working with iFrames in different browsers, there can be challenges. For example, in Internet Explorer (IE), we can effectively use the onreadystatechange event to track changes in an iFrame's content when using document.write. However, this meth ...

Pause rendering of Three.js when the video texture needs to be updated

I attempted to apply a video as a texture on a mesh, and tried two different examples: and Both examples worked fine online but didn't display anything when downloaded from GitHub. When I added the code: videoTexture.needsUpdate = false; the floo ...

What is the best way to extract an item from ng-repeat and create a hyperlink to a different webpage?

I am working with HTML code in AngularJS: <li ng-show="subCategory.status =='Active' || subCategory.status =='active'" ng-repeat="subCategory in subCategories"> <a href=""> <strong ng-click="addDetails(su ...

Is it possible for the code to display the value from the previous refresh rather than the most recent value added?

In my project, there is a functionality where a column of buttons in a table triggers a script to read the data associated with the clicked button and send it to another PHP file: <!-- Script that retrieves lecturer details for SHOW functionality - ...

Trigger the scrolling of one div when another div is scrolled

Link to Jsfiddle I'm attempting to activate my current scroll while I am outside that scroll, specifically in #DivDet Here is the code snippet of what I have tried so far: $("div#DivDet").scroll(function () { // Still trying to figure out what ...

Retrieve the JSON file only upon the first input change

On my backend, I have a JSON file containing suggested words for autocomplete in the search field. To improve performance, I don't want the JSON to load every time the page loads; instead, I only want it to load when someone wants to use the search f ...

Determining the Presence of a Value in an Array Field within a Document

Consider a group of individuals named users: { "name" : "Doe", "books": ["b1", "b2"] }, { "name" : "Jhon", "books": ["b1", "b3"] } Is there ...

The alert message fails to appear during an Ajax request

I'm having trouble understanding why the Ajax function in this code snippet is not triggering the success or error functions: function get_cust_key(custid) { $.ajax({ type: "POST", url: 'http://localhost/Test/index.php/getCust ...

Ways to automatically scroll the page to the top when new content is loaded on a Single Page Application

I've recently integrated the Single Page Application Plugin in my website built with octoberCMS and also included smooth-scrollbar.js. While most things are working smoothly, there's one issue I'm facing - smooth-scrollbar doesn't auto ...

What is the data type returned by mapping an array in TypeScript?

I am working on a function that handles sorting columns export const handleSortableColumns = (headerKeys: string[], sortKeys: object): string[] => { if (!headerKeys) return []; return headerKeys.map((key: string): any => sortKeys[key] || null); ...

What is the process for comparing two objects in TypeScript?

There is a unique class named tax. export class tax { private _id: string; private _name: string; private _percentage: number; constructor(id: string = "", taxName: string = "", percentage: number = 0) { thi ...

The ideal scenarios for employing functional setState

Lately, I've been delving into the world of React, immersing myself in tutorials and explanations on how to manipulate elements in different ways. One aspect that has caught my interest is the setState function, which allows you to update or override ...

utilizing firestore in a node.js environment

I am facing an issue while attempting to access Firestore from an Express API. I want to define a module with the Firestore initialization and export it so I can use it anywhere in my API with the require statement. Here's what I have been trying: co ...

Angular: Datepipe displays '01/01/0001' for NULL data retrieved from Database

When utilizing the DatePipe, does Angular automatically bind '01/01/0001' if we attempt to bind a NULL date value from the database? ...

Is it possible in Angular to first escape HTML strings and then add HTML markup?

Working with a search form in Angular that pulls data from a database and includes an array of strings, I implemented a pipe to highlight the search query in the results by wrapping it with <mark></mark>. This feature has been quite useful so f ...

The issue of THREE.js failing to render .obj files with .mtl files has been a common problem when exporting assets

After further investigation, it seems that the issue lies with the exported files and their formatting, although I am unsure of the exact problem. Interestingly, additional example models I downloaded render perfectly fine. I have encountered a problem wi ...

Determine the height of an element within an ng-repeat directive once the data has been fetched from an

After sending an ajax request to fetch a list of products, I use angular's ng-repeat to render them. I am attempting to retrieve the height of a div element that contains one product in the list. However, the console always displays "0" as the result ...