饥人谷技术博客

任务21-正则表达式

2016-08-03  本文已影响57人  嘿菠萝

问答

代码题


<pre>

//提示: el为dom元素,cls为操作的class, el.className获取el元素class

function addClass(el, cls){
   if(!hasClass(el,cls)){
  return el.className+=(""+cls);
   }
}

// 参考老师的写法,有点不理解:
function hasClass(el, cls) {
var reg = new RegExp('(\s|^)'+cls+'(\s|$)');
return reg.test(el.className);
}

function removeClass(el, cls) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
  tmp = node.className.replace(reg, '').replace(/\s{2,}/g, ' '); //把两个以上的空格替换为一个空格
el.className = trim(tmp);

}

</pre>


<pre>
var re = /#[0-9a-zA-Z]{6}/g;
var subj = "color: #121212; background-color: #AA00ef; width: 12px; bad-colors: f#fddee #fd2 ";
alert( subj.match(re) ) ; // #121212,#AA00ef
</pre>


输出结果及原因:
<pre>
var str = 'hello "hunger" , hello "world"';
var pat = /".*"/g;
str.match(pat);

//    /".\*"/g; 匹配的内容为"任意个任意字符",因为*默认为贪婪模式,所以会尽可能多地匹配符合正则的内容,输出结果为:[""hunger" , hello "world""]

</pre>

</pre>
改写方案1:
<pre>
var str = 'hello "hunger" , hello "world"';
var pat = /".*?"/g; //?改为非贪婪模式
str.match(pat);
</pre>

改写方案2:
<pre>
var str = 'hello "hunger" , hello "world"';
var pat=/"[^"]+"/g;
str.match(pat);

</pre>


<pre>
//贪婪模式:
var re = /<[^>]+>/;
var str = '<> <a href="/"> <input type="radio" checked> <b>';
str.match(re);
// '<a href="/">', '<input type="radio" checked>', '<b>';
//非贪婪模式:
var re = /<[^>]+?>/g;
var str = '<> <a href="/"> <input type="radio" checked> <b>';
str.match(re);
</pre>

.

上一篇下一篇

猜你喜欢

热点阅读