返回不带斜杠的字符串

Rya*_*yan 165 javascript string trailing-slash

我有两个变量:

site1 = "www.somesite.com";  
site2 = "www.somesite.com/";  
Run Code Online (Sandbox Code Playgroud)

我想做这样的事情

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;
}
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

Cha*_*ndu 430

试试这个:

function someFunction(site)     
{     
    return site.replace(/\/$/, "");
} 
Run Code Online (Sandbox Code Playgroud)

  • 要处理带有多个尾部斜杠的情况,可以使用:`return site.replace(/\/ + $ /,"");` (112认同)
  • "/".replace(/\/$/,"")将是""."/"是一个有效的路径,不应该被剥离. (12认同)
  • 请小心“/\/+$/”,它位于此处的评论中,在撰写本文时已被点赞 150 次。它受 ReDoS 约束。在很多情况下这并不重要,但如果您在服务器端 Node.js 代码中使用它(例如),可能会成为一个大问题。 (4认同)
  • @Gourav `函数removeAllTrailingSlashes(str) {let i = str.length; while (str[--i] === '/'); 返回 str.slice(0, i+1);}` (3认同)

Thi*_*ter 76

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

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


Set*_*day 37

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

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

  • 2019年最佳解决方案 (2认同)

Chr*_*LLC 29

我使用正则表达式:

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 ($)
}
Run Code Online (Sandbox Code Playgroud)

但是,您需要确保该变量site是一个字符串.

  • 我完全同意,无论何时编写正则表达式,它都应该包含在具有描述性名称或注释的函数中. (3认同)

Ste*_*n R 11

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

单尾斜杠:

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

单个或连续的尾部斜杠:

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

单前导斜线:

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

单个或连续的前导斜杠:

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

单个前导和尾随斜杠:

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

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

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

为了处理这两个斜线和斜线,更换的情况下,\/[\\/]

  • 这里的一些解决方案,例如“/\/+$/g”,很容易受到 ReDoS 的影响,因此,如果在服务器端代码上使用,则必须小心。 (2认同)

1ve*_*ven 9

此代码段更准确:

str.replace(/^(.+?)\/*?$/, "$1");
Run Code Online (Sandbox Code Playgroud)
  1. 它不会剥离/字符串,因为它是一个有效的URL.
  2. 它剥离带有多个尾部斜杠的字符串.


vde*_*nne 7

我知道这个问题是关于拖尾斜线但我在搜索修剪斜线(头部和尾部斜线)时偶然发现了这篇文章,这篇帖子帮助我解决了我的问题,所以这里是如何修剪一个或多个斜杠字符串的开头和结尾:

'///I am free///'.replace(/^\/+|\/+$/g, ''); // returns 'I am free'
Run Code Online (Sandbox Code Playgroud)

  • 如果要修剪斜杠和反斜杠: `.replace(/^[\\/]+|[\\/]+$/g, '')` (2认同)