在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 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短