返回不带斜杠的字符串

发布于 2024-11-20 00:13:48 字数 343 浏览 8 评论 0原文

我有两个变量:

site1 = "www.somesite.com";  
site2 = "www.somesite.com/";  

我想做这样的事情

function someFunction(site)
{
    // If the var has a trailing slash (like site2), 
    // remove it and return the site without the trailing slash
    return no_trailing_slash_url;
}

我该怎么做?

I have two variables:

site1 = "www.somesite.com";  
site2 = "www.somesite.com/";  

I want to do something like this

function someFunction(site)
{
    // If the var has a trailing slash (like site2), 
    // remove it and return the site without the trailing slash
    return no_trailing_slash_url;
}

How do I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

燕归巢 2024-11-27 00:13:48

试试这个:

function someFunction(site)     
{     
    return site.replace(/\/$/, "");
} 

Try this:

function someFunction(site)     
{     
    return site.replace(/\/$/, "");
} 
幽梦紫曦~ 2024-11-27 00:13:48

ES6 / ES2015 提供了一个 API 来询问字符串是否以某些内容结尾,这使得可以编写更清晰、更易读的函数。

const stripTrailingSlash = (str) => {
    return str.endsWith('/') ?
        str.slice(0, -1) :
        str;
};

ES6 / ES2015 provides an API for asking whether a string ends with something, which enables writing a cleaner and more readable function.

const stripTrailingSlash = (str) => {
    return str.endsWith('/') ?
        str.slice(0, -1) :
        str;
};
待天淡蓝洁白时 2024-11-27 00:13:48
function stripTrailingSlash(str) {
    if(str.substr(-1) === '/') {
        return str.substr(0, str.length - 1);
    }
    return str;
}

注意:IE8 及更早版本不支持负 substr 偏移量。如果您需要支持那些古老的浏览器,请使用 str.length - 1

function stripTrailingSlash(str) {
    if(str.substr(-1) === '/') {
        return str.substr(0, str.length - 1);
    }
    return str;
}

Note: IE8 and older do not support negative substr offsets. Use str.length - 1 instead if you need to support those ancient browsers.

万劫不复 2024-11-27 00:13:48

我会使用正则表达式:

function someFunction(site)
{
// if site has an end slash (like: www.example.com/),
// then remove it and return the site without the end slash
return site.replace(/\/$/, '') // Match a forward slash / at the end of the string ($)
}

不过,您需要确保变量 site 是一个字符串。

I'd use a regular expression:

function someFunction(site)
{
// if site has an end slash (like: www.example.com/),
// then remove it and return the site without the end slash
return site.replace(/\/$/, '') // Match a forward slash / at the end of the string ($)
}

You'll want to make sure that the variable site is a string, though.

一场信仰旅途 2024-11-27 00:13:48

基于@vdegenne的答案...如何剥离:

单个尾部斜杠:

theString.replace(/\/$/, '');

单个或连续尾部斜杠:

theString.replace(/\/$/, ''); Replace(/\/+$/g, '');

单前导斜杠:

theString.replace(/^\//, '');

单前导斜杠或连续前导斜杠:

theString.replace(/^\/+/g, '');

单前导和尾随斜杠:

theString.replace(/^\/|\/$/g, '')

单个或连续的前导和尾随斜杠:

theString.replace(/^\/+|\/+$/g, '')

处理斜杠和后 em>斜杠,替换实例\/[\\/]

Based on @vdegenne 's answer... how to strip:

Single trailing slash:

theString.replace(/\/$/, '');

Single or consecutive trailing slashes:

theString.replace(/\/+$/g, '');

Single leading slash:

theString.replace(/^\//, '');

Single or consecutive leading slashes:

theString.replace(/^\/+/g, '');

Single leading and trailing slashes:

theString.replace(/^\/|\/$/g, '')

Single or consecutive leading and trailing slashes:

theString.replace(/^\/+|\/+$/g, '')

To handle both slashes and backslashes, replace instances of \/ with [\\/]

甩你一脸翔 2024-11-27 00:13:48

我知道问题是关于尾部斜杠,但我在搜索修剪斜杠(在字符串文字的尾部和头部)时发现了这篇文章,因为人们需要这个解决方案,我在这里发布一个:

'///I am free///'.replace(/^\/+|\/+$/g, ''); // returns 'I am free'

更新:

正如 @Stephen R 在评论中提到的,如果你想删除字符串文字尾部和头部的斜杠和反斜杠,你可以这样写:

'\/\\/\/I am free\\///\\\\'.replace(/^[\\/]+|[\\/]+$/g, '') // returns 'I am free'

I know the question is about trailing slashes but I found this post during my search for trimming slashes (both at the tail and head of a string literal), as people would need this solution I am posting one here :

'///I am free///'.replace(/^\/+|\/+$/g, ''); // returns 'I am free'

UPDATE:

as @Stephen R mentioned in the comments, if you want to remove both slashes and backslashes both at the tail and the head of a string literal, you would write :

'\/\\/\/I am free\\///\\\\'.replace(/^[\\/]+|[\\/]+$/g, '') // returns 'I am free'
梦醒时光 2024-11-27 00:13:48

此代码段更准确:

str.replace(/^(.+?)\/*?$/, "$1");
  1. 它不会删除 / 字符串,因为它是有效的 url。
  2. 它去除带有多个尾部斜杠的字符串。

This snippet is more accurate:

str.replace(/^(.+?)\/*?$/, "$1");
  1. It not strips / strings, as it's a valid url.
  2. It strips strings with multiple trailing slashes.
鸩远一方 2024-11-27 00:13:48
function stripTrailingSlash(text) {
    return text
        .split('/')
        .filter(Boolean)
        .join('/');
}

另一个解决方案。

function stripTrailingSlash(text) {
    return text
        .split('/')
        .filter(Boolean)
        .join('/');
}

another solution.

喵星人汪星人 2024-11-27 00:13:48

我知道的最简单的方法是:

function stripTrailingSlash(str){
   if(str.charAt(str.length-1) == "/"){ str = str.substr(0, str.length - 1);}
   return str
}

更新ES2015版本。

const stripTrailingSlash = str=>str.charAt(str.length-1)=="/"?str.substr(0,str.length-1):str;

然后,这将检查末尾是否有 / ,如果存在,请将其删除。如果不是,它将按原样返回您的字符串。

修复了字符串上从零开始的索引的计算。

编辑:
由于对一个响应有评论,现在有更多人在做同样的事情,不要使用子字符串进行比较,当您可以使用 charAt< 时,您将在内存中(在低级别)创建一个全新的字符串/code> 为了获得单个字符,需要更少的内存来进行比较,Javascript 仍然是 JIT,并且无法将优化达到编译器可以达到的任何语言级别,它不会为您解决这个问题。

The easiest way I know of is this:

function stripTrailingSlash(str){
   if(str.charAt(str.length-1) == "/"){ str = str.substr(0, str.length - 1);}
   return str
}

Updates ES2015 version.

const stripTrailingSlash = str=>str.charAt(str.length-1)=="/"?str.substr(0,str.length-1):str;

This will then check for a / on the end and if it's there, remove it. If it's not, it will return your string as it was.

Fixed the calculation for zero-based index on the string.

EDIT:
As there was a comment to one response there are now more doing the same thing do not use sub string for a comparison, you're creating a whole new string in memory (at the low level) when you can use charAt to get a single char a lot less memory to do your comparison, Javascript is still JIT and can't do the optimisations to the level any lang going though a compiler can, it won't fix this for you.

他夏了夏天 2024-11-27 00:13:48
const url = new URL("https://some.site/some/path/?somekey=somevalue");
url.pathname.endsWith('/') && (url.pathname = url.pathname.slice(0, -1));
url.toString() // 'https://some.site/some/path?qk=213&hded=444';
const url = new URL("https://some.site/some/path/?somekey=somevalue");
url.pathname.endsWith('/') && (url.pathname = url.pathname.slice(0, -1));
url.toString() // 'https://some.site/some/path?qk=213&hded=444';
×眷恋的温暖 2024-11-27 00:13:48

这是一个小网址示例。

var currentUrl = location.href;

if(currentUrl.substr(-1) == '/') {
    currentUrl = currentUrl.substr(0, currentUrl.length - 1);
}

记录新网址

console.log(currentUrl);

Here a small url example.

var currentUrl = location.href;

if(currentUrl.substr(-1) == '/') {
    currentUrl = currentUrl.substr(0, currentUrl.length - 1);
}

log the new url

console.log(currentUrl);
凉城凉梦凉人心 2024-11-27 00:13:48

如果您正在使用 URL,那么您可以使用内置的 URL 类

const url = new URL('https://foo.bar/');
console.log(url.toString()); // https://foo.bar

In case you are working with URLs then you can use the built-in URL class

const url = new URL('https://foo.bar/');
console.log(url.toString()); // https://foo.bar
无言温柔 2024-11-27 00:13:48
function someFunction(site) {
  if (site.indexOf('/') > 0)
    return site.substring(0, site.indexOf('/'));
  return site;
}
function someFunction(site) {
  if (site.indexOf('/') > 0)
    return site.substring(0, site.indexOf('/'));
  return site;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文