[英]Javascript Regex constructor to match string, and ignore null, undefined, or empty strings
I'm trying to add regular expressions to only match non-null values.我正在尝试添加正则表达式以仅匹配非空值。 What I've tried below breaks the application as there are some names
, ages
, and genders
that are undefined and null in the database.我在下面尝试的操作会破坏应用程序,因为数据库中有一些未定义的names
、 ages
和genders
以及 null。 I'm trying to find a regex that will ignore the null, undefined, or empty values in the database, and only match on values that exist.我试图找到一个正则表达式,它将忽略数据库中的 null、未定义或空值,并且只匹配存在的值。
I understand ^(?.\s*$).+
will match any string that contains at least one non-space character.我了解^(?.\s*$).+
将匹配任何包含至少一个非空格字符的字符串。 But I'm struggling with how to add this to the action.payload
(the string I'm matching against).但我正在努力解决如何将它添加到action.payload
(我匹配的字符串)。
case FILTER_USERS:
return {
...state,
user_info: state.userArr.filter(user => {
const regex = new RegExp(`${action.payload}`, "gi");
return (
user.name.match(regex)
|| user.age.match(regex)
|| user.gender.match(regex)
);
})
};
I know this is very incorrect, but this is what I tried: const regex = new RegExp(`(^?)${action.payload}(.\s*$),+)`; "gi");
我知道这是非常不正确的,但这就是我尝试过的: const regex = new RegExp(`(^?)${action.payload}(.\s*$),+)`; "gi");
const regex = new RegExp(`(^?)${action.payload}(.\s*$),+)`; "gi");
Any help would be appreciated - thank you!任何帮助将不胜感激 - 谢谢!
Placing (?=^[^\s]$)
in front of your regex will assert there's at least one non-whitespace character in the match.将(?=^[^\s]$)
放在正则表达式前面将断言匹配中至少有一个非空白字符。
If you're already checking to make sure that the string isn't only whitespace, why not use if(${action.payload})
instead?如果您已经在检查以确保字符串不仅是空格,那么为什么不使用if(${action.payload})
代替呢? This will detect both empty strings and null strings, since they're both falsey.这将检测空字符串和null 字符串,因为它们都是假的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.