문제
문자열을 받아서 그 안에 있는 모든 점(.) 모양을 대시(-)로 바꾸는 JavaScript 함수를 작성해야 합니다.
입력
const str = 'this.is.an.example.string';
출력
const output = 'this-is-an-example-string';
문자열 str의 모든 점(.) 모양은 대시(-)로 대체됩니다.
예시
다음은 코드입니다 -
const str = 'this.is.an.example.string';
const replaceDots = (str = '') => {
let res = "";
const { length: len } = str;
for (let i = 0; i < len; i++) {
const el = str[i];
if(el === '.'){
res += '-';
}else{
res += el;
};
};
return res;
};
console.log(replaceDots(str)); 코드 설명
str 문자열을 반복하고 현재 요소가 점인지 확인하고 res 문자열에 대시를 추가하지 않으면 현재 요소를 추가했습니다.
출력
this-is-an-example-string