JavaScript

replace(), replaceAll() - JavaScript

폴리프레임 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>