[String] replace() 정규표현식 regular expression

Sejung Seo·2022년 6월 19일
0

JavaScript

목록 보기
12/19
post-thumbnail

modifier 종류

  • g : global 전제 모든 문자열 변경
  • i : ignore 영문 대소문자를 무시

g

let str = "apple, banana, orange, banana";
let replaced_str = str.replace('banana', "tomato");
let replaced_str_g = str.replace(/banana/g, "tomato");

console.log("변경 전 : ", str);					//결과값: apple, banana, orange, banana
console.log("변경 후 : ", replaced_str);			//결과값: apple, tomato, orange, banana
console.log("변경 후(g) : ", replaced_str_g);	//결과값: apple, tomato, orange, tomato

g 를 사용하지 않으면, 첫 문자만 치환되고 그뒤의 문자는 치환되지 않습니다.
g를 사용할 경우, 모든 문자를 치환해줍니다.

i

let str = "apple, banana, orange";
let replaced_str = str.replace('Banana', "tomato");
let replaced_str_i = str.replace(/Banana/i, "tomato");

console.log("변경 전 : ", str);					//결과값: apple, banana, orange
console.log("변경 후 : ", replaced_str);			//결과값: apple, banana, orange
console.log("변경 후(i) : ", replaced_str_i);	//결과값: apple, tomato, orange

i 를 사용하지 않으면, 대·소문자를 구분하여 치환되지 않습니다.
i 를 사용할 경우, 대·소문자를 구분하지않고 치환해줍니다.

gi

let str = "apple, banana, orange, banana";
let replaced_str_g = str.replace(/banana/g, "tomato");
let replaced_str_i = str.replace(/Banana/i, "tomato");
let replaced_str_gi = str.replace(/Banana/gi, "tomato");

console.log("변경 전 : ", str);					//결과값: apple, banana, orange, banana
console.log("변경 후(g) : ", replaced_str_g);	//결과값: apple, tomato, orange, tomato
console.log("변경 후(i) : ", replaced_str_i);	//결과값: apple, tomato, orange, banana
console.log("변경 후(gi) : ", replaced_str_gi);	//결과값: apple, tomato, orange, tomato

g를 사용할 경우, 모든 banana문자를 tomato로 치환해줍니다.
i를 사용할 경우, banana의 대·소문자를 구분하지않고 첫문자를 tomato로 치환해줍니다.
gi를 사용할 경우, 대·소문자를 구분하지않고 모든 banana를 tomato로 치환해줍니다.

profile
공부하는 코린이 🌼

0개의 댓글