<p>看过错误集锦之后才知道,is开头的函数返回值需要是bool,之前写的函数没有更改,在此说明一下。
</p>
1.\d,\w,\s,[a-zA-Z0-9],\b,.,*,+,?,x{3},^$分别是什么?
- \d 所有数字
- \w 所有字符
- \s 空格
- [a-zA-Z0-9]字母和数字
- \b 单词边界
- . 代替除换行和回车的字符
- *零个或多个字符{0,}
- +一个或多个字符{1,}
- ?零个或一个字符{0,1}
- x{3}x的数量为3
- ^以此开头
- $以此结尾
2.贪婪模式和非贪婪模式指什么?
- 贪婪模式是指在匹配成功的前提下,尽可能多的匹配
- 非贪婪就是在匹配成功的前提下,尽可能少的匹配
3.写一个函数trim(str),去除字符串两边的空白字符
<pre>
var str = ' hello world ';
function trim(str){
return str.replace(/^\s+|\s+$/g,'');
}
</pre>
<pre>
//不太明白这些个函数为什么不行呢?
function trim2(str){
if(/^\s+|\s+$/g.test(str)){
str.replace(/^\s+/,'');
str.replace(/\s$+/,'');
console.log(str);
}
}
//经过自己的实验,发现这里有一个str到底有没有被修改的问题,就是类似于闭包的问题,
//不过这里console.log里的str到底在哪声明的还是不懂,
//希望老师讲解一下这里的变量作用域。
//下面是修改过后的函数,好使了。
function trim2(str){
if(/^\s+|\s+$/g.test(str)){
var str2;
str2 = str.replace(/^\s+|\s+$/g,'');
console.log(str2);
}
}
</pre>
4.使用实现 addClass(el, cls)、hasClass(el, cls)、removeClass(el,cls),使用正则
<pre>
//提示: el为dom元素,cls为操作的class, el.className获取el元素的class
</pre>
<pre>
//函数写出来了,但是不知道怎么测试
function addClass(el,cls){
if (!hasClass(el,cls)){
el.className += ' ' + cls;
}
}
function hasClass(el,cls){
return /\bcls\b/g.test(el.className);
}
function removeClass(el,cls){
if(hasClass(el,cls)){
el.className.replace(cls,'');
}
}
</pre>
5.写一个函数isEmail(str),判断用户输入的是不是邮箱
<pre>
function isEmail(str){
if(/^\w+@\w+.\w+$/g.test(str)){
console.log("y");
}else {
console.log("n");
}
}
</pre>
6.写一个函数isPhoneNum(str),判断用户输入的是不是手机号
<pre>
function isPhoneNum(str){
if(/^1[3456789]\d{9}$/.test(str)){
console.log("y");
}else {
console.log("n");
}
}
</pre>
7.写一个函数isValidUsername(str),判断用户输入的是不是合法的用户名(长度6-20个字符,只能包括字母、数字、下划线)
<pre>
function isValid(str){
if (/\w{6,20}/.test(str)) {
console.log("y");
}else {
console.log("n");
}
}
</pre>
8.写一个函数isValidPassword(str), 判断用户输入的是不是合法密码(长度6-20个字符,包括大写字母、小写字母、数字、下划线至少两种)
<pre>
//这个虽然写出来了,但是感觉测试用的样例总是不全面。。。不知道写的是否完善。
function isValidP(str){
if (str.length < 6 || str.length > 20) {
console.log("n");
}else if (/\W/.test(str)) {
console.log("n");
}else if (/_+$|[A-Z]+$|[a-z]+$|[0-9]+$/) {
console.log("n");
}else {
console.log("y");
}
}
</pre>
9.写一个正则表达式,得到如下字符串里所有的颜色(#121212)
<pre>
var re = /#[A-z0-9]{6}/g;
var subj = "color: #121212;
background-color: #AA00ef;
width: 12px;
bad-colors: f#fddee #fd2 "
alert( subj.match(re) ) // #121212,#AA00ef
</pre>
10.下面代码输出什么? 为什么? 改写代码,让其输出hunger, world.
<pre>
var str = 'hello "hunger" , hello "world"';
var pat = /".*"/g;
str.match(pat);
//输出[""hunger" , hello "world""],pat代表匹配两个双引号之间尽可能多的字符
</pre>
<pre>
var str = 'hello "hunger" , hello "world"';
var pat = /"\w+"/g;
str.match(pat);
</pre>
11.补全如下正则表达式,输出字符串中的注释内容. (可尝试使用贪婪模式和非贪婪模式两种方法)
<pre>
str = '.. .. .. '
re = /.. your regexp ../str.match(re) /
/ '', ''
</pre>
<pre>
//贪婪模式
str = '.. .. .. ';
re = //g;
str.match(re);
</pre>
<pre>
//非贪婪模式
str = '.. .. .. ';
re = //g;
str.match(re);
</pre>
12.补全如下正则表达式
<pre>
var re = /<[A-z\s"=/]+>/g
var str = '<> <a href="/"> <input type="radio" checked> < b >'
str.match(re)
</pre>
版权归ENVY和饥人谷所有,转载请注明出处
网友评论