-1

我有一个输入字段,它接受来自用户的 url,我需要像这样检查斜杠:

  • www.example.com(添加斜线)
  • www.exaple.com/(忽略)
  • www.example.com/index.php(忽略)

我如何在 JavaScript 中实现这一点?

PS .htaccess 和 php 不是选项

4

3 回答 3

1

试试这个 -

function URLFormat() {
    var url = document.getElementById('inputURL').value;
    var urlParts = url.split("/")
    var result = '';
    for (i = 0; i < urlParts.length; i++) {
        if (i == urlParts.length - 1) {
            if (urlParts[i].indexOf('.') > -1) {
                // trailing slash not required
                result = url;
            }
            else {
                if (urlParts[i].indexOf('#') > -1) {
                    // trailing slash not required
                    result = url;
                }
                else {
                    //Assume this is a folder and add a slash
                    result = url + '/';
                }
            }
        }
    }
    alert(result);
}
于 2012-04-10T09:34:36.030 回答
0
var input = "http://www.example.com";
var hasTrailingSlash = input.charAt(input.length - 1) === "/";
于 2012-04-09T10:33:26.717 回答
0

试试这个

function func(url) {
     var domain = url.split("/")[0];
     var answer;
     if(url == domain){
       answer = url + "/";
     } else {
       answer = url;
     }
     alert(answer);
}
于 2012-04-09T11:41:30.393 回答