方法一、使用split函数和filter函数
function deleteSpace(str){
// split将字符串按单个字符变为数组
return str.split('').filter((itemstr)=>{
// filter循环遍历,itemstr为空格返回空字符,否则返回字符
return itemstr==' '?'':itemstr
// join再把数组链接成字符串
}).join('')
}
方法二、 使用split函数和join函数
function deleteSpace(str){
// split将字符串按空格分隔为数组,join再把数组链接成字符串
return str.split(' ').join('')
}
方法三、使用正则
function deleteSpace(str){
// 匹配所有空格字符(至少一个),将其变为''
return str.replace(/\s+/g,'')
}
方法四、递归(锻炼思维)
function deleteSpace(str){
// 出口(字符串中无空格)
if(str.indexOf(' ')==-1){
return str
}
else {
//return str.substring(0,str.indexOf(' ')) + deleteSpace(str.substring(str.indexOf(' ')).trim())
// concat拼接
// 举例:"123 456 777 8"
// str.substring(0,str.indexOf(" ")) => "123"
// str.substring(str.indexOf(" ")) => " 456 777 8"
// 空格在后半句所以需要使用trim()去除前后空格
return str.substring(0,str.indexOf(" ")).concat(deleteSpace(str.substring(str.indexOf(" ")).trim()));
}
}
Comments 1 条评论
Warning: 获取IP地理位置失败 in /www/wwwroot/blog.zbcode.cn/wp-content/themes/Sakurairo-2.7.2/inc/classes/IpLocation.php on line 226
Unknown
博客很酷炫。