Search code examples
javascriptnode.jsjsonstringify

How to remove all occurrences of string in Javascript


I am using JSON.stringify to convert object into string as follows:

JSON.stringify(obj).replace(/[{}]/g, '').slice(1, -1)

I am getting below output:

"null,null,"Heading":"Heading1""

I want to remove all occurrences of null from the above string, for which I am using replace

JSON.stringify(obj).replace(/[{}]/g, '').slice(1, -1).replace('null,', '')

But it only removes the first occurrence of null string

 "null,"Heading":"Heading1""

Desired output:

"Heading":"Heading1""

Solution

  • As peeps said in comments may be the best way for this is to get rid of null element in the first place, so if you want to do that you should iterate through your object then check for null items.

    For this cause this may come handy:

    Object.keys(obj).forEach((key) => (obj[key] == null) && delete obj[key]);
    

    Otherwise, you should consider using a global flag (/g) in your regex, in order to remove all null occurrence.

    You can achieve this with something like this:

    .replace(/null,/g, '')