programing

후행 슬래시 없이 문자열 반환

bestcode 2022. 11. 8. 21:49
반응형

후행 슬래시 없이 문자열 반환

두 가지 변수가 있습니다.

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 이전 버전은 마이너스 기판 오프셋을 지원하지 않습니다.사용하다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그래도 끈이야.

@vdegenne의 답변을 바탕으로...분해 방법:

단일 후행 슬래시:

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

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

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

단일 선행 슬래시:

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

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

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

단일 선행 및 후행 슬래시:

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

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

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

슬래시와 백슬래시를 모두 처리하려면 의 인스턴스를 바꿉니다.\/와 함께[\\/]

이 질문은 슬래시에 대한 질문인 것은 알지만, 이 게시물은 트리밍 슬래시(스트링 리터럴의 꼬리부분과 머리부분 모두)를 검색하던 중 발견되었습니다.이러한 해결방법이필요하기때문에여기서1개를올립니다.

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

갱신:

코멘트에서 설명한 것처럼 문자열 리터럴의 끝부분과 선두부분에서 슬래시와 백슬래시를 모두 삭제하려면 다음과 같이 입력합니다.

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

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

str.replace(/^(.+?)\/*?$/, "$1");
  1. 벗겨지지 않는다/유효한 URL이므로 스트링을 지정합니다.
  2. 여러 개의 후행 슬래시가 있는 문자열을 제거합니다.
function stripTrailingSlash(text) {
    return text
        .split('/')
        .filter(Boolean)
        .join('/');
}

다른 해결책입니다.

다음은 작은 URL의 예입니다.

var currentUrl = location.href;

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

새 URL 기록

console.log(currentUrl);

제가 아는 가장 쉬운 방법은 다음과 같습니다.

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비교에 필요한 메모리를 1개라도 더 적게 얻기 위해 Javascript는 여전히 JIT이며 컴파일러가 할 수 있는 수준까지 최적화를 할 수 없습니다.이것은 수정되지 않습니다.

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

언급URL : https://stackoverflow.com/questions/6680825/return-string-without-trailing-slash

반응형