Viết hàm thay thế mọi khoảng trắng trong chuỗi bằng %20 (URL encoding).
Ví dụ: 'some extra Space' → 'some%20extra%20%20Space'.
Ví dụ
const str = 'some extra Space';
const replaceWhitespace = (str = '') => {
let res = '';
const { length } = str;
for (let i = 0; i < length; i++) {
const char = str[i];
res += (char === ' ') ? '%20' : char;
}
return res;
};
console.log(replaceWhitespace(str));
Kết quả
some%20extra%20%20Space