[javascript] 슬래시없이 문자열 반환

두 가지 변수가 있습니다.

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

어떻게해야합니까?



답변

이 시도:

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


답변

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

참고 : IE8 및 이전 버전은 음의 substr 오프셋을 지원하지 않습니다. str.length - 1고대 브라우저를 지원해야하는 경우 대신 사용하십시오 .


답변

ES6 / ES2015는 문자열이 무언가로 끝나는 지 묻는 API를 제공하여보다 깔끔하고 읽기 쉬운 기능을 작성할 수 있습니다.

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


답변

정규식을 사용합니다.

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그러나 변수 가 문자열 인지 확인하고 싶을 것 입니다.


답변

이 스 니펫이 더 정확합니다.

str.replace(/^(.+?)\/*?$/, "$1");
  1. /유효한 URL이므로 문자열을 제거하지 않습니다 .
  2. 후행 슬래시가 여러 개인 문자열을 제거합니다.

답변

나는 슬래시 후행에 관한 질문을 알고 있지만 사람들 이이 솔루션을 필요로하기 때문에 슬래시 트리밍 (문자열 리터럴의 꼬리와 머리 모두)을 검색하는 동안이 게시물을 찾았습니다.

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

최신 정보 :

@Stephen R이 코멘트에 언급 둘 다 슬래시와 꼬리와 문자열 리터럴의 머리에 백 슬래시를 모두 제거하려면, 당신은 작성합니다 :

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


답변

@vdegenne의 답변을 바탕으로 … 제거하는 방법 :

단일 후행 슬래시 :

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

단일 또는 연속 후행 슬래시 :

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

단일 선행 슬래시 :

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

단일 또는 연속 선행 슬래시 :

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

단일 선행 및 후행 슬래시 :

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

단일 또는 연속 선행 및 후행 슬래시 :

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

모두 슬래시 및 처리하기 위해 다시 슬래시의 인스턴스 교체 \/로를[\\/]