replace()

이일우·2023년 3월 20일

공부하기

목록 보기
18/42

replace는 자바스크립트에서 문자열을 다루는데 있어 매우 유용한 메서드입니다.

replace

replace는 문자열에서 특정 문자열을 찾아 다른 문자열로 대체하는 기능입니다..

str.replace(searchValue, replaceValue);

위와 같이 사용 할 수 있습니다. 위 코드는 문자열str에서 searchValuereplaceValue로 바꾸는 기능을 합니다.

예제

const str = "I like apple.";
const newStr = str.replace("apple", "orange");
console.log(newStr); // "I like orange."

위 코드에서와 같이 사용할 수 있습니다.

정규식과 함께 사용하기

replace는 정규식과 함께 사용하면 활용도가 더욱 높습니다.

const stringWithSpaces = "Hello, World! This is a test.";
const stringWithoutSpaces = stringWithSpaces.replace(/\s+/g, "");
console.log(stringWithoutSpaces); // "Hello,World!Thisisatest."

위 코드는 문자열에서 모든 공백을 제거하는 기능을 합니다. /\s+/는 공백 문자에 대한 정규식
g는 전역 검색을 의미합니다.

const stringWithNumbers = "My numbers are 2, 4, and 8.";
const stringWithSquares = stringWithNumbers.replace(/\d+/g, (match) => match * match);
console.log(stringWithSquares); // "My numbers are 4, 16, and 64."

위 코드는 문자열에서 모든 숫자를 찾아 해당 숫자의 제곱으로 대체합니다.
/\d+/g 문자열에서 모든 숫자를 찾습니다.
(match) => match * match는 숫자를 찾을 때마다 해당 숫자의 제곱으로 대체하는 함수입니다.

이처럼 replace 메서드와 정규식을 함께 사용하면 다양한 문자열 처리 작업을 손쉽게 수행할 수 있습니다.

마치며

replace메서드를 사용하여 문자열의 특정 부분을 바꿀 수 있습니다. 특히 정규식과 함께 사용 시 문자열을 효율적으로 변환 시킬 수 있습니다.

참고자료 출처

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/replace

0개의 댓글