1、字符串替换
需求:有字符串“Once1a2wolf,3always4a5wolf!”,
写代码实现最终输出结果“Once a wolf, always a wolf!”
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
var s = "Once1a2wolf,3always4a5wolf!";
var regex = /\d+/g;
var s2 = s.replace(regex, " ");
alert(s2);
</script>
2、字符串切割
需求:请按照叠词切割“sdqqfgkkkhjppppkl”
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
s = 'sdqqfgkkkhjppppkl';
regex = /(.)\1+/;
var arr = s.split(regex);
// console.log(arr);
s = 'sdqqfgkkkhjppppkl';
regex = /(.)\1+/g;
var s2 = s.replace(regex, " ");
var arr = s2.split(' ');
alert(arr);
</script>
3、字符串替换
需求:将字符串“我我....我...我.要...要要...要学....学学..学.编..编编.编.程.程.程..程”还原成“我要学编程”
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
var s = "我我....我...我.要...要要...要学....学学..学.编..编编.编.程.程.程..程";
var regex = /\.+/g;
var s2 = s.replace(regex, "").match(/(.)\1+/g);
var s3=''
for(i in s2){
s3+=s2[i][0]
}
alert(s3);
</script>
4、字符串获取
需求:把一个字符串"我的手机号码是17688888888,曾经用过13187654321,还用过13512345678"中的手机号码获取出来
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
// regex = /^1[567]\d{8}$/;
var s = '我的手机号码是17688888888,曾经用过13187654321,还用过13512345678';
var regex = /1[567]\d{9}/g;
var arr = s.match(regex);
alert(arr);//["17688888888","13187654321","13512345678"]
</script>
网友评论