简体   繁体   English

如何删除 Javascript 中所有出现的字符串

[英]How to remove all occurrences of string in Javascript

I am using JSON.stringify to convert object into string as follows:我正在使用JSON.stringify将 object 转换为字符串,如下所示:

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

I am getting below output:我低于 output:

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

I want to remove all occurrences of null from the above string, for which I am using replace我想从上面的字符串中删除所有出现的 null,为此我正在使用replace

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

But it only removes the first occurrence of null string但它只删除了第一次出现的null字符串

 "null,"Heading":"Heading1""

Desired output:所需的 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.正如评论中所说,最好的方法可能是首先摆脱null元素,所以如果你想这样做,你应该遍历你的 object 然后检查null项目。

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.否则,您应该考虑在您的正则表达式中使用全局标志 ( /g ) ,以删除所有null出现。

You can achieve this with something like this:您可以通过以下方式实现此目的:

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

The.replace() method only replaces the first occurrence. .replace() 方法只替换第一次出现。 Perform global replacement as执行全局替换为

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

Hope it helps!希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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