Skip to content

Instantly share code, notes, and snippets.

@QuadFlask
Created May 3, 2016 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save QuadFlask/28973fa8818646522534f4c5b96ec9f0 to your computer and use it in GitHub Desktop.
Save QuadFlask/28973fa8818646522534f4c5b96ec9f0 to your computer and use it in GitHub Desktop.
[CodeWars] strip url params
Complete the method so that it does the following:
  • Removes any duplicate query string parameters from the url
  • Removes any query string parameters specified within the 2nd argument (optional array)
Examples:
stripUrlParams('www.codewars.com?a=1&b=2&a=2') // returns 'www.codewars.com?a=1&b=2'
stripUrlParams('www.codewars.com?a=1&b=2&a=2', ['b']) // returns 'www.codewars.com?a=1'
stripUrlParams('www.codewars.com', ['b']) // returns 'www.codewars.com'
www.codewars.com?a=1&b=2&a=3

이런 url 에서 중복된 param 제거 및 배열로 받은 인자 제외 시키기

My Solution

function stripUrlParams(url, paramsToStrip=[]){
	var regex = /([?&]((\w+)=(\w+)))/g;
	var result = regex.exec(url);
	var tokens = [];
	var paramKey = {};

	while (result) {
		if (!paramKey[result[3]] && !paramsToStrip.some(p=> p==result[3])) {
			paramKey[result[3]] = true;
			tokens.push(result.slice(2));
		}
		result = regex.exec(url);
	}

	var r = /.+\?/g;
	var withoutParam = r.exec(url)||url;

	return withoutParam + tokens.map(t=>t[0]).join('&');
}

음... 정규식이 장난 아니네...

Best Practice

function stripUrlParams(url, paramsToStrip){
  return url.replace(/&?([^?=]+)=.+?/g, function(m, p1, qPos) {
    return url.indexOf(p1 + '=') < qPos || (paramsToStrip||[]).indexOf(p1) > -1 ? "": m;
   });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment