String string = new String("가나가나다라")
String text = string.replace("가", "!");
System.out.println(text);
// !나!나다라 출력
String string = new String("가나가나다라")
String text = string.replaceAll("가", "!");
System.out.println(text);
// !나!나다라 출력
String string = new String("가나가나다라")
String text = string.replaceFirst("가", "!");
System.out.println(text);
// !나가나다라 출력
메서드 str.replace(regexp, replacement)
를 사용하면 str
내 부분 문자열 중 regexp
에 일치하는 부분 문자열을 replacement
로 교체할 수 있다. 이때 플래그 g
가 있으면 모든 부분 문자열이 교체되고, 그렇지 않으면 첫 번째 부분 문자열만 교체된다.
// 플래그 g 없음
alert( "We will, we will".replace(/we/i, "I") ); // I will, we will
// 플래그 g 있음
alert( "We will, we will".replace(/we/ig, "I") ); // I will, I will