상세 컨텐츠

본문 제목

replace(), replaceAll() - JavaScript

JavaScript

by 폴리프레임 2024. 5. 11. 10:14

본문

반응형

1. replace() 메서드

replace() 메서드는 문자열에서 첫 번째로 발견된 부분만을 대체합니다. 이 메서드는 두 개의 인자를 받습니다: 첫 번째는 찾을 패턴(문자열 또는 정규 표현식), 두 번째는 그 패턴을 대체할 문자열입니다.

let text = "Hello World, welcome to my World.";
let newText = text.replace("World", "Planet Earth");
console.log(newText);  // "Hello Planet Earth, welcome to my World."

 

정규표현식으로, i는 대소문자 구분 안함

let text = "Hello world, welcome to the World.";
let newText = text.replace(/world/i, "Planet Earth");
console.log(newText);  // "Hello Planet Earth, welcome to the World."

 

 

2. replaceAll() 메서드

replaceAll() 메서드는 문자열 내의 모든 일치하는 문자열 또는 정규 표현식 패턴을 지정된 문자열로 대체합니다. 이 메서드도 두 개의 인자를 받습니다: 첫 번째는 찾을 패턴, 두 번째는 그 패턴을 대체할 문자열입니다.

let text = "Hello World, welcome to the World.";
let newText = text.replaceAll("World", "Planet Earth");
console.log(newText);  // "Hello Planet Earth, welcome to the Planet Earth."
// next.js에서 params.slug가 like-this-shape 일때
<h1>
    <span className="block text-base text-center text-primary font-semibold tracking-wide uppercase">
        Syng Yang - {`${(params.slug).replaceAll("-", " ")}`}
    </span>          
</h1>

'JavaScript' 카테고리의 다른 글

객체접근, 배열접근 - JavaScript  (0) 2024.05.13
반짝이는 효과 - tailwindcss  (0) 2024.05.12
세미콜론 " ; " - 자바스크립트  (0) 2024.05.11
<noscript> 태그  (0) 2024.05.11
Sanity - Next.js - Vercel Depoly  (1) 2024.05.10

관련글 더보기