RegExp搜索无法正常工作

时间:2016-10-06 18:32:03

标签: javascript regex

我有一个反应组件,并且我想在值onchange上进行RegExp搜索。每次输入更改时,下面的函数都会运行,但结果没有意义。注销为true的测试(regex.test(usr.email))不会通过过滤函数中的if语句...

search(data) {
    const { dispatch, users, filteredUsers } = this.props;
    const query = data.q || data.target.value;
    let sanitisedQuery;
    if (query === '' && filteredUsers.length < users.length) {
      console.log('empty string reset');
      return dispatch(setFilteredUsers([...users]));
    }

    if (query) {
      sanitisedQuery = query.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
      const regex = new RegExp(sanitisedQuery, 'gi');
      const fUsers = users.filter((usr) => {
        if (regex.test(usr.email)) {
          return usr;
        }
      });
      dispatch(setFilteredUsers(fUsers));
    }
  }

我已经把原木拿出来让它更清楚,但我得到的是:

?d41d:60 query r string
?d41d:63 regex /r/gi
?d41d:65 email <redacted> true //<-- the true is regex.test(usr.email)
?d41d:65 email <redacted> true
?d41d:67 returning user 
Object {email: <second email>, ...}
?d41d:65 email <redacted> false
?d41d:65 email <redacted> true
?d41d:65 email <redacted> false
?d41d:71 fUsers 
[Object]
?d41d:158 about to dispatch SET_FILTERED_USERS 
[Object]
?d41d:38 action 
Object {type: "SET_FILTERED_USERS", filteredUsers: Array[1]}
?d41d:114 user 
Object {email: <second email>, …}

每个电子邮件都经过测试,第一个,第二个和第四个电子邮件通过了测试,但只有第二个电子邮件被传递到新数组中。

0 个答案:

没有答案