首页 > 处理html字符串的正则表达式

处理html字符串的正则表达式

不是很会使用正则表达式,求各位帮忙看下一个需求

有一段html的字符串,如下

html<p>看<span style="font-size: 15px; line-height: 1.5;">图说话</span></p>
<p><img src="http://a.com/1.png" alt=""></p>
<p> </p>
<p> </p>
<p>再来一张图片</p>
<p><img src="http://a.com/2.png" alt="" width="609" height="590"></p>

需要能够针对字符串中的img标签做如下处理:
1. 加上 width="100%" height="auto",如果img已经存在width和hegiht,需要先去掉
2. 增加一个onlick事件,传入img的src作为参数

期待的结果是

html<p>看<span style="font-size: 15px; line-height: 1.5;">图说话</span></p>
<p><img src="http://a.com/1.png" alt="" width="100%" height="auto" onlick="foo('http://a.com/1.png')"></p>
<p> </p>
<p> </p>
<p>再来一张图片</p>
<p><img src="http://a.com/2.png" alt="" width="100%" height="auto" onlick="foo('http://a.com/2.png')"></p>

var str = '<p>看<span style="font-size: 15px; line-height: 1.5;">图说话</span></p>\
    <p><img src="http://a.com/1.png" alt=""></p>\
    <p> </p>\
    <p> </p>\
    <p>再来一张图片</p>\
    <p><img src="http://a.com/2.png" alt="" width="609" height="590"></p>';

function query( str, callback ) {
    var d = document.createElement("div");
    d.innerHTML = str;
    return callback( d );
}

str = query( str, function( dom ) {
    [].forEach.call( dom.querySelectorAll(dom), function(img) {
        img.setAttribute("width", "100%"),
        img.setAttribute("height", "auto"),
        img.setAttribute("onclick", "foo('"+ img.src +"')")
    })
    return dom.innerHTML;
})

Regex不太會, 但是用JavaScript還是可以的.

js(function(){
  $('img').each(function(){
    $this = $(this);
    $this.attr({
        width: '100%',
        height: 'auto',
        onclick: "foo('" + $this.attr('src') + "')"
    });
  });
}());
【热门文章】
【热门文章】