달나라 노트

Google Apps Script : replace, replaceAll (텍스트 바꾸기) 본문

Google Apps Script

Google Apps Script : replace, replaceAll (텍스트 바꾸기)

CosmosProject 2022. 11. 21. 21:00
728x90
반응형

 

 

 

replace(), replaceAll() method는 둘 다 문자열에서 특정 텍스트를 어떠한 다른 텍스트로 바꿔줍니다.

 

 

Syntax

string.replace(text_before, text_after)
string.replaceAll(text_before, text_after)

 

일반적인 replace() method사용법과 비슷합니다.

 

string에 적용할 수 있으며 2개의 인자를 받습니다.

 

text_before = string에서 찾아낼 text

text_after = 새롭게 대체할 text

 

replace()와 replaceAll()의 차이는 다음과 같습니다.

 

replace()는 string에서 text_before를 찾고 가장 처음 찾아진 text만을 text_after로 바꿉니다.

즉, string에서 text_before가 여러 개 찾아졌다고 해도 가장 왼쪽에 있는 하나만을 바꾸는 것이죠.

 

그런데 replaceAll()은 string에 존재하는 모든 text_before를 text_after로 바꿉니다.

 

 

 

예시를 봅시다.

 

function myFunction() {
  var test_string = 'apple_banana_peach_watermelon_pineapple';

  test_string = test_string.replace('apple', '@');
  Logger.log(test_string);
}


-- Result
@_banana_peach_watermelon_pineapple

 

- test_string = test_string.replace('apple', '@');

test_string에서 apple이라는 글자를 찾아서 at sign(@)으로 바꿉니다.

 

apple_banana_peach_watermelon_pineapple

여기서 apple은 총 2군데 존재합니다.

그러나 replace() method는 가장 먼저 찾아진 하나만을 대체하죠.

 

그래서 결과도 가장 처음 apple이 사라지고 @로 대체되었습니다.

 

 

 

 

 

 

 

 

function myFunction() {
  var test_string = 'apple_banana_peach_watermelon_pineapple';
  
  test_string = test_string.replaceAll('apple', '@');
  Logger.log(test_string);
}


-- Result
@_banana_peach_watermelon_pine@

 

이전과 동일하지만 replaceAll() method를 사용하였습니다.

 

apple_banana_peach_watermelon_pineapple

여기서 apple은 총 2군데 존재합니다.

 

근데 replaceAll() method는 모든 apple을 찾아 텍스트를 변경하기 때문에

존재하는 모든 apple이라는 텍스트가 @로 바뀌었습니다.

 

@_banana_peach_watermelon_pine@

그래서 결과는 위와 같죠.

 

 

 

 

 

 

728x90
반응형
Comments