使用JavaScript向URL添加尾部斜杠

时间:2012-04-09 10:30:58

标签: javascript

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

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

我怎样才能在javaScript中实现这个目标?

PS .htaccess和php不是选项

3 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

var input = "http://www.example.com";
var hasTrailingSlash = input.charAt(input.length - 1) === "/";

答案 2 :(得分:0)

试试这个

function func(url) {
     var domain = url.split("/")[0];
     var answer;
     if(url == domain){
       answer = url + "/";
     } else {
       answer = url;
     }
     alert(answer);
}