Javascript + Typescript/이론과 문법
문자열의 특정 문자 변경하기
치춘
2023. 8. 8. 13:24
문자열의 특정 문자 변경하기
let string = "hello world";
string[2] = "a";
console.log(string);
자바스크립트에서는 문자열의 특정 문자를 인덱스를 통해 변경할 수 없다
인덱스가 문자열의 특정 문자의 포인터를 가리키는 C언어 등과 다르게 자바스크립트는 문자의 참조를 가리키지 않기 때문
그럼 어떻게
let string = "hello world";
string = string.substring(0, 2) + "a" + string.substring(3);
console.log(string);
문자열을 잘라서 다시 이어붙이는 수고를 해야 한다
쩝
function replaceAt(string, index, replace) {
return string.substring(0, index) + replace + string.substring(index + 1);
}
let string = "hello world";
string = replaceAt(string, 2, "a");
console.log(string);
replaceAt
함수를 구현해두면 위와 같다
String.prototype.replaceAt = function (index, replace) {
return this.substring(0, index) + replace + this.substring(index + 1);
};
let string = "hello world";
string = string.replaceAt(2, "a");
console.log(string);
String
객체의 프로토타입 메서드로 추가하면 어떠한 문자열 타입 변수들도 지역적으로 replaceAt
을 이용할 수 있다
참고 자료
https://stackoverflow.com/questions/8392035/add-method-to-string-class