开发者

Return string without trailing slash

开发者 https://www.devze.com 2023-03-19 20:25 出处:网络
I have two variables: site1 = \"www.somesite.com\"; site2 = \"www.somesite.com/\"; I want to do something like this

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 site开发者_如何学运维2), 
    // remove it and return the site without the trailing slash
    return no_trailing_slash_url;
}

How do I do this?


Try this:

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


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


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.


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.


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 [\\/]


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'


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.


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

another solution.


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);


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.


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


function someFunction(site) {
  if (site.indexOf('/') > 0)
    return site.substring(0, site.indexOf('/'));
  return site;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号