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)
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)
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是一个字符串.
Ste*_*n R 11
基于@vdegenne 的回答......如何剥离:
单尾斜杠:
theString.replace(/\/$/, '');
单个或连续的尾部斜杠:
theString.replace(/\/+$/g, '');
单前导斜线:
theString.replace(/^\//, '');
单个或连续的前导斜杠:
theString.replace(/^\/+/g, '');
单个前导和尾随斜杠:
theString.replace(/^\/|\/$/g, '')
单个或连续的前导和尾随斜线:
theString.replace(/^\/+|\/+$/g, '')
为了处理这两个斜线和回斜线,更换的情况下,\/与[\\/]
此代码段更准确:
str.replace(/^(.+?)\/*?$/, "$1");
Run Code Online (Sandbox Code Playgroud)
/字符串,因为它是一个有效的URL.我知道这个问题是关于拖尾斜线但我在搜索修剪斜线(头部和尾部斜线)时偶然发现了这篇文章,这篇帖子帮助我解决了我的问题,所以这里是如何修剪一个或多个斜杠字符串的开头和结尾:
'///I am free///'.replace(/^\/+|\/+$/g, ''); // returns 'I am free'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
104655 次 |
| 最近记录: |