javascript/jquery将尾部斜杠添加到url(如果不存在)

javascript/jquery将尾部斜杠添加到url(如果不存在),javascript,jquery,validation,Javascript,Jquery,Validation,我正在制作一个小的web应用程序,用户在其中输入一个服务器URL,通过AJAX请求从中提取数据 由于用户必须手动输入URL,人们通常会忘记尾随斜杠,即使它是必需的(因为一些数据会附加到输入的URL中)。我需要一种方法来检查斜杠是否存在,如果不存在,请添加斜杠 这似乎是一个jQuery需要一行程序来解决的问题,有人知道怎么做吗?或者我应该为它编写一个JS函数吗 var lastChar = url.substr(-1); // Selects the last character if (last

我正在制作一个小的web应用程序,用户在其中输入一个服务器URL,通过AJAX请求从中提取数据

由于用户必须手动输入URL,人们通常会忘记尾随斜杠,即使它是必需的(因为一些数据会附加到输入的URL中)。我需要一种方法来检查斜杠是否存在,如果不存在,请添加斜杠

这似乎是一个jQuery需要一行程序来解决的问题,有人知道怎么做吗?或者我应该为它编写一个JS函数吗

var lastChar = url.substr(-1); // Selects the last character
if (lastChar != '/') {         // If the last character is not a slash
   url = url + '/';            // Append a slash to it.
}
临时变量名可以省略,并直接嵌入到断言中:

if (url.substr(-1) != '/') url += '/';
由于目标是使用一行程序更改url,因此也可以使用以下解决方案:

url = url.replace(/\/?$/, '/');
  • 如果尾部斜杠存在,则替换为
    /
  • 如果尾部斜杠不存在,则在末尾追加一个
    /
    (确切地说,尾部锚定将替换为
    /

您可以执行以下操作:

var url = 'http://stackoverflow.com';

if (!url.match(/\/$/)) {
    url += '/';
}

以下是证据:

我添加到正则表达式解决方案中以适应查询字符串:

url+=url.endsWith(“/”)?"" : "/"

在找到这个问题及其答案之前,我创建了自己的方法。我把它贴在这里,因为我没有看到类似的东西

function addSlashToUrl() {
    //If there is no trailing shash after the path in the url add it
    if (window.location.pathname.endsWith('/') === false) {
        var url = window.location.protocol + '//' + 
                window.location.host + 
                window.location.pathname + '/' + 
                window.location.search;

        window.history.replaceState(null, document.title, url);
    }
}

不是每个URL都可以用斜杠结尾。至少有几个条件不允许这样做:

  • 最后一个斜杠后面的字符串类似于
    index.html
  • 有一些参数:
    /page?foo=1&bar=2
  • 有指向片段的链接:
    /page#tomato
我已经编写了一个函数,用于在上述情况都不存在时添加斜杠。还有两个附加函数用于检查添加斜杠的可能性和将URL分解为多个部分。最后一个不是我的,我已经给了一个原始的链接

const SLASH='/';
函数appendslashtourlifispable(url){
var resultingUrl=url;
var slashAppendingPossible=slashAppendingIsPossible(url);
如果(可能发生){
结果URL+=斜杠;
}
返回结果URL;
}
函数slashAppendingIsPossible(url){
//在以下情况下,可以将斜杠添加到url的末尾:
//-没有斜杠作为URL的最后一个符号。
//-没有文件扩展名(或者称为文件名的部分中没有点)。
//-没有参数(即使是空参数-URL末尾的单个参数)。
//-没有指向片段的链接(即使是空的片段-URL末尾有一个#标记)。
var slashappendingmable=false;
var parsedUrl=parseUrl(url);
//检查是否缺少斜杠。
var path=parsedUrl.path;
var lastCharacterInPath=path.substr(-1);
var noSlashInPathEnd=lastCharacterInPath!==SLASH;
//检查分机是否缺勤。
常量文件\u扩展名\u REGEXP=/\.[^.]*$/;
var noFileExtension=!FILE_EXTENSION_REGEXP.test(parsedUrl.FILE);
//检查是否缺少参数。
var noParameters=parsedUrl.query.length==0;
//检查片段缺失的链接。
var noLinkToFragment=parsedUrl.hash.length==0;
//以上所有检查都不能保证URL末尾没有“?”或“#”符号。
//需要手动检查。
变量NO_SLASH_HASH_或_QUESTION_MARK_AT_STRING_END_REGEXP=/[^\/#?]$/;
var nostopcharactersatheendofrelativepath=NO\u斜杠\u哈希\u或\u问号\u字符串\u结束\u REGEXP.test(parsedUrl.relative);
slashappendingmable=noSlashInPathEnd&&noFileExtension&&noParameters&&noLinkToFragment&&nostopcharactersatheendorrelativepath;
返回可能发生的事件;
}
//parseUrl函数基于以下函数:
// http://james.padolsey.com/javascript/parsing-urls-with-the-dom/.
函数解析url(url){
var a=document.createElement('a');
a、 href=url;
常量默认值_字符串=“”;
var getParametersAndValues=函数(a){
var参数和值={};
const QUESTION_MARK_IN_STRING_START_REGEXP=/^\?/;
常量参数_分隔符='&';
常量参数_值_分隔符='='';
var PARAMETERS和valuesstrings=a.search.replace(字符串中的问号、起始字符串、默认字符串)。split(参数分隔符);
var parametersAmount=Parameters和ValuesString.length;
for(让index=0;indexfunction addSlashToUrl() {
    //If there is no trailing shash after the path in the url add it
    if (window.location.pathname.endsWith('/') === false) {
        var url = window.location.protocol + '//' + 
                window.location.host + 
                window.location.pathname + '/' + 
                window.location.search;

        window.history.replaceState(null, document.title, url);
    }
}
url = url.replace(/\/$|$/, '/');
let urlWithoutSlash = 'https://www.example.com/path';
urlWithoutSlash = urlWithoutSlash.replace(/\/$|$/, '/');
console.log(urlWithoutSlash);

let urlWithSlash = 'https://www.example.com/path/';
urlWithSlash = urlWithoutSlash.replace(/\/$|$/, '/');
console.log(urlWithSlash);
https://www.example.com/path/
https://www.example.com/path/
You would use the url module like this: 
const url = require ('url');
let jojo = url.parse('http://google.com')
console.log(jojo);
var url = document.getElementsByTagName('a')[0];
var myURL = "http://stackoverflow.com";
console.log(myURL.href);