Dev./javascript
[JS] 파일 이름으로 사용할 수 없는 문자만 인코딩하기
인쥭
2023. 2. 8. 17:19
반응형
Windows를 기준으로 사용할 수 없는 문자는 \/:*?"<>|이고, 파일 명은 온점(.)으로 끝나지 않아야 한다.
요 내용을 정규식으로 표현하면,
const regex = /([\\/:*?\"<>|])|(\.$)/g;
이제 이걸 토대로 String.prototype.replace와 encodeURIComponent를 조합하면 결과는 다음과 같다.
const regex = /([\\/:*?\"<>|])|(\.$)/g;
const target = '<>/\:?"<>|:\':S.text*.';
const result1 = target.replace(regex, (match) => {
return encodeURIComponent(match);
});
console.log(result1); // %3C%3E%2F%3A%3F%22%3C%3E%7C%3A'%3AS.text*. 가 출력됨
보다시피 마지막 온점과 *이 인코딩되지 않는데, 이유는 다음 링크에서 확인할 수 있다.
encodeURIComponent() - JavaScript | MDN
encodeURIComponent() 함수는 URI의 특정한 문자를 UTF-8로 인코딩해 하나, 둘, 셋, 혹은 네 개의 연속된 이스케이프 문자로 나타냅니다. (두 개의 대리 문자로 이루어진 문자만 이스케이프 문자 네 개로
developer.mozilla.org
해결 방법도 해당 문서에서 찾을 수 있으며, 다음과 같이 인코딩 로직을 손수 작성해주면 문제를 해결할 수 있다.
const regex = /([\\/:*?\"<>|])|(\.$)/g;
const target = '<>/\:?"<>|:\':S.text*.';
const result1 = target.replace(regex, (match) => {
return encodeURIComponent(match);
});
console.log(result1); // %3C%3E%2F%3A%3F%22%3C%3E%7C%3A'%3AS.text*. 가 출력됨
const result2 = target.replace(regex, (match) => {
return `%${match.charCodeAt(0).toString(16).toUpperCase()}`;
});
console.log(result2); // %3C%3E%2F%3A%3F%22%3C%3E%7C%3A'%3AS.text%2A%2E 가 출력됨
/* 결과 비교
result1: %3C%3E%2F%3A%3F%22%3C%3E%7C%3A'%3AS.text*.
result2: %3C%3E%2F%3A%3F%22%3C%3E%7C%3A'%3AS.text%2A%2E
*/