skip to Main Content

I am working on some front end task , where I am showing some APIs response on UI
The thing is in my API response I am getting some messages which includes ‘n’.
So wherever ‘n’ is coming I want to append a new line here, means whatever data that is coming after ‘n’ from APIs it should go to the new line.

Below is format which I am getting from my rest API response.

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

Attached Screenshot for the same.

enter image description here

Now the thing is in the innerError ‘n’ is coming and this message I am displaying on the UI on some pop-up.

I tried the below methods

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

after the above approach when tried to print the data on console it is working fine.
but on the UI it is not getting displayed correctly.

2. I first replaced the 'n' with <br> then changing it to 'n' 

In the screenshot you can see that data is coming but it is not getting displaying in the new line.

can someone tell how to achieve this requirement.

Thanks in Advance!

2

Answers


  1. You can apply white-space: pre-line on the element via CSS. It will collapse when overflowing the container, and add a line break at newline characters. Demo:

    const myText = 'memoery xyz has no labelsnResource abc is in use and cannot be removed';
    document.getElementById('my-element').innerHTML = myText;
    #my-element {
      white-space: pre-line;
    }
    <span id="my-element"></span>
    Login or Signup to reply.
  2. Is this what you want? (Replace n with \n before parsing the JSON string and make sure that your JSON string is valid)

        var strJSON='{"errors":[{"code":"rm.config.unableToSet","innerError":"memoery xyz has no labelsnResource abc is in use and cannot be removed","logref":"c8a6f244-188e-4512-85c1-88788","message":"Unable to set data to DB"}]}'
        
        strJSON= strJSON.replace(/n/g,'\n')
    
        const obj = JSON.parse(strJSON);
    
        alert(obj.errors[0].innerError);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search