Javascript 函数模式匹配

Javascript Function pattern matching

我在测验中遇到了这个 javascript 问题。下面的代码 returns 正确。但我不知道如何。谁能解释一下

主题标题:与 JavaScript

的模式匹配

以下代码返回什么值?

function test(form) {
  var str = "apples, oranges, bananas, melons";
  var re = /apple/i;
  var testStr = re.test(str);
  document.write(testStr + "<BR>");
  //Outputs - true 
 }

它在字符串 str 中搜索 apple 的出现并输出是否找到它。

根据w3schools documentation

The test() method tests for a match in a string.

This method returns true if it finds a match, otherwise it returns false.

因为 /apple/i 正则表达式将匹配任何包含 apple 的字符串,其中忽略字母的大小写,即它也将匹配 AppleAPPLE 等., 由于字符串 apples, oranges, bananas, melons 包含 apple test() 方法 returns true.

HTML DOM write()

The write() method writes HTML expressions or JavaScript code to a document.

The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.

因此,document.write(testStr + "<BR>");方法调用将测试结果写入文档。

请阅读 Mozilla 基金会关于 test() 的文档,其中:

  • 语法
  • 描述
  • 例子
  • 规格
  • 浏览器兼容性
  • 等等

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

以下示例来自 Mozilla 基金会:

function testinput(re, str){
    var midstring;

    if (re.test(str)) {
        midstring = ' contains ';
    } else {
        midstring = ' does not contain ';
    }
    console.log(str + midstring + re.source);
}