javascript/jquery add trailing slash to url (if no

2020-05-22 06:54发布

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.

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.

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?

8条回答
冷血范
2楼-- · 2020-05-22 07:53

You can do something like:

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

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

Here's the proof: http://jsfiddle.net/matthewbj/FyLnH/

查看更多
不美不萌又怎样
3楼-- · 2020-05-22 07:54
url += url.endsWith("/") ? "" : "/"
查看更多
登录 后发表回答