Search

문자열1_개념04_문자수정

대분류
STEP09 문자열
문제 난이도
필수
소분류
문자열1_개념

영상

개념

<script> /* [개념] 문자열 수정 시 주의점 자바스크립트에서는 문자열을 변경할 수 없다. 처음부터 새로 변수를 만들거나 replace() 함수를 사용해야 한다. */ // [문제] hello에서 e를 a로 변경하시오. // [방법1] let text = "hello"; text[1] = "a"; // 직접 수정은 불가능하다. document.write(text + "<br>"); // hello let newText = ""; for(let i=0; i<text.length; i++) { if(text[i] == "e") { newText += "a"; } else { newText += text[i]; } } document.write(newText + "<br>"); /* [개념] 문자열 교체 let 변수 = "문자열"; 변수 = 변수.replace(교체전, 교체후); 문자열의 일부를 교체할 때 사용한다. */ // [방법2] text = text.replace("e", "a"); document.write(text + "<br>"); // hallo text = "Hong's number is 010-1234-5678."; let result = text.replace("Hong's", "Kim's"); document.write(result); </script>
Java
복사