DEV Community

Love The Earth🐱✌🏻
Love The Earth🐱✌🏻

Posted on

Getting undefined error for string variable

We are creating a simple search application with ReactJS and NextJS. We are searching Elasticsearch indexes. It's been going well, but now I need to make some results look better. I'm getting a field back when doing a search, which is a JSON object full of \n\n characters (after using JSON.stringify on the object) that I need to convert to carriage returns.

When I just use the value of this field in a browser, it's one long string. When I attempt to do:
let fc = JSON.stringify(fieldname);
newfc = fc.replace("\n", ""); // for example - I really need to use br

I get "fc undefined". But fc displays properly until I try to use replace or split, or any method on it. I have no errors in the console.

Why am I getting undefined on this string? Is there another way I should be converting \n to carriage returns?

Top comments (1)

Collapse
 
amcgrath815 profile image
Love The Earth🐱✌🏻

I figured this out! I was getting an "undefined" error on the records that did not have the field I was using in the fc variable. I added a condition to check for this, and am no longer getting the error.