javascript / jquery将尾部斜杠添加到url(如果不存在) [英] javascript/jquery add trailing slash to url (if not present)

查看:96
本文介绍了javascript / jquery将尾部斜杠添加到url(如果不存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个小型网络应用,用户输入一个服务器网址,通过AJAX请求从中提取大量数据。

I'm making a small web app in which a user enters a server URL from which it pulls a load of data with an AJAX request.

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

Since the user has to enter the URL manually, people generally forget the trailing slash, even though it's required (as some data is appended to the url entered). I need a way to check if the slash is present, and if not, add it.

这似乎是一个问题,jQuery会有一个单行,有人知道怎么做或者我应该为它写一个JS函数吗?

This seems like a problem that jQuery would have a one-liner for, does anyone know how to do this or should I write a JS function for it?

推荐答案

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.
}

临时变量名可以省略,并直接嵌入断言中: / p>

The temporary variable name can be omitted, and directly embedded in the assertion:

if (url.substr(-1) != '/') url += '/';

由于目标是使用单行更改网址,因此还可以使用以下解决方案:

Since the goal is changing the url with a one-liner, the following solution can also be used:

url = url.replace(/\/?$/, '/');




  • 如果尾随斜杠存在,则替换为 /

  • 如果尾部斜杠不存在,则在末尾附加 / (确切地说:尾部锚点替换为 / )。

    • If the trailing slash exists, it is replaced with /.
    • If the trailing slash does not exist, a / is appended to the end (to be exact: The trailing anchor is replaced with /).
    • 这篇关于javascript / jquery将尾部斜杠添加到url(如果不存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆