JavaScript/Tip

[JavaScript]URL에서 Query String 제거하는 방법

DevStory 2022. 10. 6.

URL에서 Query String 제거하는 방법

URL의 Query String은 물음표(?)부터 시작하는 Key=Value 형식을 말합니다. 주로 Naver와 Google 또는 검색 기능이 있는 웹 사이트에서 특정 키워드를 검색하는 경우 해당 키워드를 Query String으로 설정합니다.

 

다음 예시는 stackabuse 사이트에서 ur이라는 단어를 검색했을 경우의 URL입니다.

https://stackabuse.com/search/?q=url

위에서 언급했듯이 Query String은 물음표(?)부터 시작하므로 Query String은 q=url입니다.

위 URL은 간단한 예시이므로 파싱 하는데, 큰 어려움이 없지만, Naver 또는 Google은 Query String이 상당히 복잡합니다.

 

다음 예시는 Naver에서 맛집이라는 단어를 검색했을 경우의 URL입니다.

https://search.naver.com/search.naver?sm=tab_hty.top&where=nexearch&query=맛집&oquery=맛집&tqi=hz19wlprvxZsscqdQmRssssst04-255238

이번 포스팅은 이러한 복잡한 URL에서 Query String을 제거할 수 있는 몇 가지 방법을 소개합니다.


방법 1. URL

가장 기본적인 방법으로 new 키워드를 사용하여 URL 객체 생성 후 해당 객체의 search 프로퍼티를 빈 문자열('')로 설정합니다. 그다음 Query String이 제거된 URL을 가져오기 위해 toString() 메서드를 호출합니다.

const strURL = 'https://search.naver.com/search.naver?sm=tab_hty.top&where=nexearch&query=맛집&oquery=맛집&tqi=hz19wlprvxZsscqdQmRssssst04-255238';

// 1. URL 객체 생성
const urlObject = new URL(strURL);

// 2. search 프로퍼티를 빈 문자열('')로 설정
urlObject.search = '';

// 3. toString() 메서드 호출
console.log(urlObject.toString()); // https://search.naver.com/search.naver

 

URL 객체의 search 프로퍼티는 물음표(?)부터 시작하는 Query String만 반환합니다. 따라서, #으로 시작하는 해시는 제거되지 않습니다.

const strURL = 'https://search.naver.com/search.naver?sm=tab_hty.top&where=nexearch&query=맛집&oquery=맛집&tqi=hz19wlprvxZsscqdQmRssssst04-255238#hash';

// 1. URL 객체 생성
const urlObject = new URL(strURL);

// 2. search 프로퍼티를 빈 문자열('')로 설정
urlObject.search = '';

// 3. toString() 메서드 호출
console.log(urlObject.toString()); // https://search.naver.com/search.naver#hash

 

Query String뿐만 아니라 #으로 시작하는 해시도 제거하고 싶은 경우 URL 객체에서 hash 프로퍼티를 빈 문자열('')로 설정합니다.

const strURL = 'https://search.naver.com/search.naver?sm=tab_hty.top&where=nexearch&query=맛집&oquery=맛집&tqi=hz19wlprvxZsscqdQmRssssst04-255238#hash';

// 1. URL 객체 생성
const urlObject = new URL(strURL);

// 2. search, hash 프로퍼티를 빈 문자열('')로 설정
urlObject.search = '';
urlObject.hash = '';

// 3. toString() 메서드 호출
console.log(urlObject.toString()); // https://search.naver.com/search.naver

방법 2. split 메서드

또 다른 방법으로 split() 메서드를 사용하여 Query String을 제거할 수 있습니다. split() 메서드는 특정 구분자를 기준으로 분리된 배열을 반환합니다.

 

Query String을 제거하기 위해 물음표(?)를 기준으로 문자열로 구성된 URL을 분리합니다.

const strURL = 'https://search.naver.com/search.naver?sm=tab_hty.top&where=nexearch&query=맛집&oquery=맛집&tqi=hz19wlprvxZsscqdQmRssssst04-255238#hash';

console.log(strURL.split('?'));
// ['https://search.naver.com/search.naver', 'sm=tab_hty.top&where=nexearch&query=맛집&oquery=맛집&tqi=hz19wlprvxZsscqdQmRssssst04-255238#hash']

split() 메서드를 사용하는 방법의 단점은 Query String 뒤에 존재하는 해시를 제거한다는 것입니다.

 

해시는 보존하고 Query String만 제거하고 싶은 경우 밑에서 소개하는 slice() 메서드를 사용하는 것이 좋습니다.


방법 3. slice 메서드

마지막 방법으로 slice() 메서드를 사용하여 시작 위치부터 마지막 위치까지 문자열을 가져올 수 있습니다.

 

시작 위치를 0으로 설정하고 마지막 위치를 물음표(?)가 위치하는 인덱스로 설정합니다.

 

물음표(?)가 위치하는 인덱스를 마지막 위치로 설정하기 위해 indexOf() 메서드를 사용합니다.

const strURL = 'https://search.naver.com/search.naver?sm=tab_hty.top&where=nexearch&query=맛집&oquery=맛집&tqi=hz19wlprvxZsscqdQmRssssst04-255238#hash';

console.log(strURL.slice(0, strURL.indexOf('?'))); // https://search.naver.com/search.naver

 

만약, 다음 예제처럼 문자열로 구성된 URL에 물음표(?)가 없는 경우 물음표(?) 앞에 있는 문자 r이 잘리는 문제가 발생합니다. indexOf() 메서드는 해당 문자열이 없으면 -1을 반환하기 때문입니다.

const strURL = 'https://search.naver.com/search.naver';

console.log(strURL.slice(0, strURL.indexOf('?'))); // https://search.naver.com/search.nave

 

따라서, includes() 메서드를 사용하여 물음표(?)가 존재하면, slice() 메서드를 호출하도록 코드를 구현합니다.

const strURL = 'https://search.naver.com/search.naver?sm=tab_hty.top&where=nexearch&query=맛집&oquery=맛집&tqi=hz19wlprvxZsscqdQmRssssst04-255238#hash';
var strURLParse = '';

if(strURL.includes('?')) {
  strURLParse = strURL.slice(0, strURL.indexOf('?'));
}

console.log(strURLParse); // https://search.naver.com/search.naver

 

해시는 보존하고 Query String만 제거하고 싶은 경우 Query String이 제거된 문자열과 #부터 시작하는 문자열을 연결합니다.

function removeQueryString(url) {
  if(url.includes('?')) {
    return url.slice(0, url.indexOf('?'));
  } else {
    return '';
  }
}

function getHash(url) {
  if(url.includes('#')) {
    return url.slice(url.indexOf('#'));
  } else {
    return '';
  }
}

const strURL = 'https://search.naver.com/search.naver?sm=tab_hty.top&where=nexearch&query=맛집&oquery=맛집&tqi=hz19wlprvxZsscqdQmRssssst04-255238#hash';

var strURLParse = removeQueryString(strURL) + getHash(strURL);

console.log(strURLParse); // https://search.naver.com/search.naver#hash
반응형

댓글