JavaScript里面的居民们3-去除空格和重复
2024-09-04 12:08:08
如代码,分别实现 diyTrim 及 removeRepetition 函数,并跑通代码中的测试用例。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>JS里的居民们3</title> </head>
<body>
<script>
/*
实现一个字符串头尾去除空格的函数
注意需要去除的空格,包括全角、半角空格
暂时不需要学习和使用正则表达式的方式
*/
function diyTrim(str) {
//遍历一下每个字符前后是否为空格,是的话进行切割字符串,直到没有空格,结束循环。
for(i=0;i<str.length;i++){
if(str[0]==" "||str[0]==" "){
str=str.slice(1);
}
else if(str[str.length-1]==" "||str[str.length-1]==" "){
str=str.slice(0,str.length-2);
}
else{
break;
}
}
return str;
} // 测试用例
console.log(diyTrim(' a f b ')); // ->a f b
console.log(diyTrim(' ffdaf ')); // ->ffdaf
console.log(diyTrim('1 ')); // ->1
console.log(diyTrim(' f')); // ->f
console.log(diyTrim(' a f b ')); // ->a f b
console.log(diyTrim(' ')); // ->
console.log(diyTrim(' ')); // ->
console.log(diyTrim('')); // -> /*
去掉字符串str中,连续重复的地方
*/
function removeRepetition(str) {
var result = ""; for(i=0,len=str.length;i<len;i++){//定义len,每次循环都会改变长度
if(str[0]==str[1]){//判断前后是否一致
str=str.slice(1);//记得赋值给str,不然就是原来的数组。
}
else{
result=result+str[0];//存入不重复的值,并且要往后继续移一个
str=str.slice(1);
}
}
return result;
} // 测试用例
console.log(removeRepetition("aaa")); // ->a
console.log(removeRepetition("abbba")); // ->aba
console.log(removeRepetition("aabbaabb")); // ->abab
console.log(removeRepetition("")); // ->
console.log(removeRepetition("abc")); // ->abc
</script>
</body>
</html>
最新文章
- Apache DdlUtils入门
- 今天写项目时,突然发现canvas的一些公式不记得了,所以整理了一番,分享给大家。
- document.createElement
- SSO系统的分析与架构
- 【转】Github轻松上手6-推荐follow的牛人和值得watch的repo
- Select模型及tcp select模型
- php 扩展编译linux
- visul svn+花生壳
- prototype vs __proto__ 之间关系
- Java调用.dll文件
- 解压tar.gz文件报错gzip: stdin: not in gzip format解决方法
- cross-document message 跨文档通信 HTML5
- oracle 数据库 date + 1 转载
- jumpserver win终端无法添加
- linux云计算面试知识汇总,文件共享--vsftpd秘籍
- MobX 学习
- Btrace介绍
- 第一讲(3)osgearth编译
- 将 numeric 转换为数据类型 numeric 时出现算术溢出错误
- sgu187&;&;spoj7734
热门文章
- 对xaml的深入探究(补交作业)
- web 应用的部署
- 微信小程序 没有找到node_modules目录 ,小程序引入vant框架报错。
- session和cookie的知识总结
- [BZOJ 4857][Jsoi2016]反质数序列
- 动态树Link-cut tree(LCT)总结
- java中比较两个日期的大小
- (转)Linux:使用libgen.h:basename,dirname
- 关于display:none;和id特性的一些需要注意的地方
- opensuse13.1 安装chrome报 error while loading shared libraries:libudev.so.0:cannot open shared object file:no file or directory