return 在函数中使用 indexOf 作为参数的子字符串

return a substring using indexOf as a parameter within a function

我应该创建一个函数来测试 URL 的有效性,然后根据某些字符的位置查找 URL 字符串的 return 部分(位置未知)。仅供参考,我对编程很陌生,但一直在寻找并尝试很多答案。我最近的尝试使用以下格式(在答案中找到)但是当我调用该函数时仍然只能显示一个空字符串。

当我在 Chrome 中 运行 并输入“http://www.niagaracollege.ca" or "http://lego.ca”时,即使我输入的是有效的 URL,我也会得到 return的错误。

function validURL(userInput)
{
    input = new String(userInput);

    if (input.indexOf("://") != -1 && input.lastIndexOf(".") != -1)
        return true;

    else
        return false;
  }

 function findProtocol(userInput)
{
    input = new String(userInput);
    var result = input.substring(0, input.indexOf("://"));
    return result;
}

function findServer(userInput)
{   
    input = new String(userInput);

    var result = input.substring(input.indexOf("://") + 1 ,input.lastIndexOf("."));

    return result;
}

function findDomain(userInput)
{
    input = new String(userInput);

    var result = input.substring(input.lastIndexOf(".") + 1);

    return result;
}

function btnReadURL_onclick()
{
    var userInput = document.getElementById("txtURL").value;

    var outputBox = document.getElementById("txtOutput");

    var URL = validURL(userInput);

    if (URL = true)
    {
       var Part1 = findProtocol(userInput);
       var Part2 = findServer(userInput);
       var Part3 = findDomain(userInput);

       outputBox.value = "Protocol: " + Part1 + "\nServer: " + Part2 + 
    "\nDomain: " + Part3;
    }   

    else (URL == true)
       outputBox.value = "Invalid URL"; 
 }

使用调试器找出您在 userInput 中获得的内容。代码很好。它应该工作。请参阅下面的示例代码。

test = function() {
    var test = "http://Test 2"
    alert(test.substring(0, test.indexOf("://")))
}

您需要将值传递给 findProtocol 方法而不是 DOM element

替换

var userInput = document.getElementById("txtURL");

来自

var userInput = document.getElementById("txtURL").value;

并替换

if (URL = true)

if( URL == true )