描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
给定的字符串长度不超过100。保证字符串中的字符为大写英文字母、小写英文字母和空格中的一种。
示例1
输入:"We Are Happy
返回值:“We%20Are%20Happy”
方法1
直接使用正则替换
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return string字符串
*/
function replaceSpace( s ) {
// write code here
return s.replace(/\s/g,'%20')
}
module.exports = {
replaceSpace : replaceSpace
};
方法2
暴力循环
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return string字符串
*/
function replaceSpace( s ) {
// write code here
let result = '';
for(let i = 0;i < s.length;i++) {
if(s[i] === ' ') {
result += '%20';
} else {
result += s[i];
}
}
return result;
}
module.exports = {
replaceSpace : replaceSpace
};
方法3
先通过空格使用split转换为数组,再通过join方法 ‘%20’ 作为分割字符串
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return string字符串
*/
function replaceSpace( s ) {
// write code here
return s.split(' ').join('%20');
}
module.exports = {
replaceSpace : replaceSpace
};
方法4
将字符串使用扩展运算符转成数组,然后使用数组的map方法
function replaceSpace( s ) {
let arr = [...s].map(item => {
return item === ' ' ? '%20' : item;
});
return arr.join('');
}
module.exports = {
replaceSpace : replaceSpace
};