프로그래밍Front-End

[Vue3, TypeScript] 특수문자 (&amp, &quot, &lt, &gt 등 치환 함수(encode, decode)

자바 Spring, 스프링부트 등 인터셉터에서 특수문자(예: <, >, & 등)가 HTML 엔티티로 치환돼서 저장되었다면, Vue 화면에 표시할 때 다시 원래 문자열로 복원해서 보여줘야 한다.

TypeScript 유틸 함수로 하나 만들어서 사용하자

// utils/customDecode.ts
export function customDecode(text?: string): string {
  if (!text) return "";

  return text
    .replace(/&amp;/g, "&")
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">")
    .replace(/&quot;/g, '"')
    .replace(/&#39;/g, "'")
    .replace(/&#40;/g, "(")
    .replace(/&#41;/g, ")");
}

사용 예시:

import { customDecode } from "@/utils/customDecode";

const originalText = customDecode(data.record.faqText);

이렇게 하면 &amp;&, &lt;< 같은 식으로 원래 값 복원돼서 화면에 표시할 수 있다.

이 함수를 반대로 저장 시에도 특수문자 치환하는 customEncode 함수도 만들어 볼 수 있다. 저장할 때 인코딩(customEncode) 함수는 아래와 같다.

// utils/customText.ts
export function customEncode(text?: string): string {
  if (!text) return "";

  return text
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;")
    .replace(/\(/g, "&#40;")
    .replace(/\)/g, "&#41;");
}

export function customDecode(text?: string): string {
  if (!text) return "";

  return text
    .replace(/&amp;/g, "&")
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">")
    .replace(/&quot;/g, '"')
    .replace(/&#39;/g, "'")
    .replace(/&#40;/g, "(")
    .replace(/&#41;/g, ")");
}

사용 예시

import { customEncode, customDecode } from "@/utils/customText";

// 저장하기 전에 치환
const saveText = customEncode(inputText);

// DB에서 꺼내와서 화면 표시할 때 복원
const displayText = customDecode(data.record.faqText);

error: Content is protected !!