在JavaScript中将空格字符串转换为url
在WebURL中,如果我们在URL中提供空格,浏览器会自动将所有空格替换为字符串'%20'
我们需要编写一个JavaScript函数,该函数将字符串作为第一个也是唯一的参数。然后,该函数应构造并返回一个新字符串,该字符串中的空格(无论位于何处)都由'%20'代替。
例如-
如果输入字符串是-
const str = 'some extra Space';
那么输出应该是-
const output = 'some%20extra%20%20Space';
示例
为此的代码将是-
const str = 'some extra Space';
const replaceWhitespace = (str = '') => {
let res = '';
const { length } = str;
for(let i = 0; i < length; i++){
const char = str[i];
if(!(char === ' ')){
res += char;
}else{
res += '%20';
};
};
return res;
};
console.log(replaceWhitespace(str));输出结果控制台中的输出将是-
some%20extra%20%20Space
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短