[Vue3, TypeScript] 특수문자 (&, ", <, > 등 치환 함수(encode, decode)
자바 Spring, 스프링부트 등 인터셉터에서 특수문자(예: <
, >
, &
등)가 HTML 엔티티로 치환돼서 저장되었다면, Vue 화면에 표시할 때 다시 원래 문자열로 복원해서 보여줘야 한다.
TypeScript 유틸 함수로 하나 만들어서 사용하자
// utils/customDecode.ts
export function customDecode(text?: string): string {
if (!text) return "";
return text
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/(/g, "(")
.replace(/)/g, ")");
}
사용 예시:
import { customDecode } from "@/utils/customDecode";
const originalText = customDecode(data.record.faqText);
이렇게 하면 &
→ &
, <
→ <
같은 식으로 원래 값 복원돼서 화면에 표시할 수 있다.
이 함수를 반대로 저장 시에도 특수문자 치환하는 customEncode
함수도 만들어 볼 수 있다. 저장할 때 인코딩(customEncode) 함수는 아래와 같다.
// utils/customText.ts
export function customEncode(text?: string): string {
if (!text) return "";
return text
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'")
.replace(/\(/g, "(")
.replace(/\)/g, ")");
}
export function customDecode(text?: string): string {
if (!text) return "";
return text
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/(/g, "(")
.replace(/)/g, ")");
}
사용 예시
import { customEncode, customDecode } from "@/utils/customText";
// 저장하기 전에 치환
const saveText = customEncode(inputText);
// DB에서 꺼내와서 화면 표시할 때 복원
const displayText = customDecode(data.record.faqText);