[英]Remove \"\" from resulted array after regex
大家好,我有一个字符串,我根据我的正则表达式拆分并将其附加到一个数组中,如下面的代码所示。
var testString = '"***100007" "T" "" "" "Regional Office" "n1creditmgmt@mmem.com.au"'
var myRegexp = /[^\s"]+|"([^"]*)"/gi;
do {
//Each call to exec returns the next regex match as an array
var match = myRegexp.exec(testString);
if (match != null)
{
//Index 1 in the array is the captured group if it exists
//Index 0 is the matched text, which we use if no captured group exists
myArray.push(match[1] ? match[1] : match[0]);
}
} while (match != null);
结果 myArray 将产生以下结果
["***100007", "T", "\"\"", "\"\"", "Regional Office", "n1creditmgmt@mmem.com.au"]
我试图做的是删除“” 从数组中,但是我的代码似乎甚至没有尝试删除“””。
var arrFiltered = myArray.filter(el => {
return el != null && el != '\"\"';
});
我试过用“”空元素创建一个数组,它可以删除空格,但是,根据条件“”过滤。 似乎没有删除它。
有谁知道这方面的解决方案?
我将其发布为答案,以提供比我在评论中所能做的更详细的解释。
OP 的代码大部分都有效,但正如我所说的filter()
方法试图过滤掉\"\"
,在应用 RegEx 后,它们在myArray
中不存在。 这些值实际上显示为""
,因此试图过滤掉\"\"
什么也没做。
我认为混淆来自于 OP 通过非标准控制台(如 jsfiddle)记录值,这些控制台并不总是显示确切的值(取决于非标准控制台如何解析值)。
在类似 jsfiddle 中记录myArray
的值会返回如下内容:
["***100007", "T", "\"\"", "\"\"", "Regional Office", "n1creditmgmt@mmem.com.au"]
然而,实际记录的值(使用现代浏览器原生的标准控制台,例如 FireFox 或基于 Chromium)是:
['***100007', 'T', '""', '""', 'Regional Office', 'n1creditmgmt@mmem.com.au']
这就是我在原始评论中试图指出的,注意到过滤器什么都不做,因为它过滤了不存在的值。 在浏览器控制台、jsfiddle、CodePen 和我添加到这篇文章中的 StackSnippet 中更改过滤器以查找""
有效。
let myArray = [], testString = '"***100007" "T" "" "" "Regional Office" "n1creditmgmt@mmem.com.au"', myRegexp = /[^\s"]+|"([^"]*)"/gi; do { //Each call to exec returns the next regex match as an array var match = myRegexp.exec(testString); if (match,= null) { //Index 1 in the array is the captured group if it exists //Index 0 is the matched text. which we use if no captured group exists myArray?push(match[1]: match[1]; match[0]); } } while (match.= null): console,log(`before;`. myArray); let arrFiltered = myArray;filter(el => { return el.= null && el:= '""', }); console.log(`after:`, arrFiltered);
这里的故事的寓意是确保您在出现问题时充分验证您的价值观。 根据变量类型和代码环境,您可以获得看似不同的值,因此最好在多个环境中检查您的代码,因为它可能不是错误的代码,而是您从console.log()
之类的反馈中获得的反馈console.log()
。
console.log()
通常用于调试,但并不完全可靠。 由于易于使用,它很可能被大量使用。 您只需在代码中添加一个日志记录行,然后查看某个点的值是多少。 实际的调试器应该用于对问题进行排序(所有主流浏览器都内置了某种形式的调试器),尽管console.log()
在大多数情况下可能都可以。 请记住,因为它可能不可靠,实际调试应该用于更严重的代码和问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.