[javascript] replace 잘 써보기

dev stefanCho·2022년 2월 24일
0

javascript

목록 보기
26/26

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. If pattern is a string, only the first occurrence will be replaced. - MDN

replace는 match된 모든 패턴을 replacement로 바꾸고, 새로운 문자열을 return 합니다.
이 패턴은 string 혹은 RegExp이 될 수 있습니다.

pattern이 string인 경우

basic usage

최초 match에 대해서 단 1개만 replace 됩니다.

let hello = 'hello! my name is stefan cho!'

hello.replace('!', '☺︎') // 'hello☺︎ my name is stefan cho!'

replacer function 사용

replace function이 최초 match에 대해서 단 1번만 호출됩니다.

let hello = 'hello! my name is stefan cho!'

hello.replace('!', function(...args) {
  console.log(args); // ['!', 5, 'hello! my name is stefan cho!']
  return '☻'
}) // 'hello☻ my name is stefan cho!'

pattern이 RegExp인 경우

basic usage

match된 결과 값이 replace 됩니다.
(예시에서 (?<=y)x는 Lookbehind assertion으로 x를 매칭시킵니다.)

let numberAndUnderScore = '123_456_789'

numberAndUnderScore.replace(/(?<=\d+)_/, '+') // '123+456_789'

위 결과가 맞는지 match method로 확인해봅시다.
match 패턴에 의해서 123을 찾았고, Lookbehind assertion에 의해 3번째 index의 ``가 매치되었습니다.
따라서 123+456_789는 타당한 결과값임이 증명되었습니다.

let numberAndUnderScore = '123_456_789'

numberAndUnderScore.match(/(?<=\d+)_/, '+') // ['_', index: 3, input: '123_456_789', groups: undefined]

global replace

모든 match값을 replace 해봅시다.
regex flag에 g(global)를 추가합니다.

let numberAndUnderScore = '123_456_789'

numberAndUnderScore.replace(/(?<=\d+)_/g, '+') // '123+456+789'

replacer function 사용

같은것을 replace function으로 만들어 봅시다.
replace function은 match되는 pattern이 있을 때 마다 호출됩니다.

numberAndUnderScore.replace(/(?<=\d+)_/g, function(...args) { 
  return '+' 
}) // '123+456+789'

세자리마다 comma(,) 찍기 Example

let money = '10000000000';
money.match(/\B(?=(\d{3})+(?!\d))/g) // ['', '', '']

money.replace(/\B(?=(\d{3})+(?!\d)/g, function(...args) {
  console.log(args);
  return ','
}) // '10,000,000,000'

money.replace(/\B(?=(\d{3})+(?!\d)/g, ',') // '10,000,000,000'

\B는 맨 앞에 ,를 찍는것을 방지하기 위해 추가되었습니다.

(\d{3})+이므로 digit의 개수가 3의 배수(3개, 6개, 9개 등)이면서 끝이 숫자가 아닌경우에 대해서 Lookahead assertion(x(?=y))으로 match되는 문자열을 찾습니다.
여기서는 x(?=y)형태에서 x값이 빈값이기 때문에(\B는 계산에서 제외됨), 해당 index의 빈문자열('')이 match된 것입니다.

match되는 케이스가 총 3번이므로 console.log는 세번 출력됩니다.

2,5,8번 index에 빈문자열을 ,로 변형하게 됩니다.

profile
Front-end Developer

0개의 댓글