简体   繁体   中英

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""

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, '')

The.replace() method only replaces the first occurrence. Perform global replacement as

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

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM