从字符串REGEX中删除字符串

时间:2016-11-23 00:31:25

标签: regex

我有一个自动生成的字符串,如下所示:

["January","February",null,"April"]

我需要从字符串中删除“,null”的任何匹配,即:

["January","February",null,"April"] --> ["January","February","April"]

如何找到除",null"以外的所有内容?

我尝试了"^(?!,null).*"的变体而没有成功。

2 个答案:

答案 0 :(得分:1)

如上所述回答您的问题,您不需要正则表达式:

str = str.replace(",null", "");

但是,要处理边缘情况:

["January","February",null,"April"] --> ["January","February","April"]
["January",null,null,"April"] --> ["January","April"]
[null,"January","February","April"] --> ["January","February","April"]
["January","February","April",null] --> ["January","February","April"]
[null] --> []

更好地服务于正则表达式:

str = str.replaceAll("(?<=\\[)null,?|,null", ""); 

替换正则表达式适用于null第一个(也可能是唯一的)位置,以及任何其他情况。

答案 1 :(得分:0)

请查看这个,我们可以使用过滤功能

var arr = [null, "January","February",null,"April", null];

var arr2 = arr.filter(function(x){return x !== null})

console.log(arr,arr2);