【问题标题】:How to get false when match finds nothing?当匹配什么都没找到时如何得到假?
【发布时间】:2018-10-22 21:14:19
【问题描述】:

当我运行这段代码时:

var foundUrlString = savedPage.match( /og:url.*="(http.*\.com)/i );
var foundUrl = foundUrlString[1];

如果页面上没有匹配项,我会收到错误消息:

表达式 'foundUrlString' [null] 的结果不是对象

当没有匹配项而不是这个错误时,我怎样才能得到“假”?

【问题讨论】:

  • 所以您希望foundUrl 成为匹配字符串或false

标签: javascript regex regex-group


【解决方案1】:

离开你所拥有的,你可以在第二行添加一个“真实”检查:

var foundUrlString = savedPage.match( /og:url.*="(http.*\.com)/i );
var foundUrl = !!foundUrlString && foundUrlString[1];

这会将foundUrl 保留为匹配字符串或false

【讨论】:

    【解决方案2】:

    选中null 以打印falsetrue

            var savedPage = '';
            var foundUrlString = savedPage.match( /og:url.*="(http.*\.com)/i );
            var foundUrl = foundUrlString == null ? false : true;
            console.log(foundUrl );

    【讨论】:

      【解决方案3】:

      以下是trycatch 的示例,可能会对您有所帮助:

      function regex(savedPage) {
        try {
          var foundUrlString = savedPage.match(/og:url.*="(http.*\.com)/i);
          return foundUrlString[1];
        } catch (error) {
          return false;
        }
      }
      var savedPage1 = '<link property="og:url" content="http://test.com/test">';
      console.log('savedPage1',regex(savedPage1));
      var savedPage2 = '<link content="http://test.com/test">';
      console.log('savedPage2',regex(savedPage2));

      【讨论】:

        【解决方案4】:

        您需要了解String.prototype.match 的用途。函数match 将在您的正则表达式中返回一个包含整组匹配组的数组。所以,如果你想验证一个字符串,最好的方法是使用函数RegExp.prototype.test

        使用正则表达式中的函数RegExp.prototype.test

        let savedPage = "EleFromStack";
        console.log(/og:url.*="(http.*\.com)/i.test(savedPage));

        【讨论】:

          猜你喜欢
          • 2011-08-26
          • 2020-12-29
          • 1970-01-01
          • 2019-04-19
          • 1970-01-01
          • 2022-08-15
          • 2020-11-27
          • 2016-10-17
          • 1970-01-01
          相关资源
          最近更新 更多