开发者

regular expression attribute replace

I am trying to work out some regular expression which I have working in one direction but fails when i change the attributes.

What I am trying to achieve is find the value of align and replace this value into the class

var s = '<img src="" align="left" class="smart" title="title for reference" />';
var reg = new Reg开发者_如何转开发Exp(/(?:align="(.*?)").*?(?:class="(.*)")/);
console.log( s.replace(reg ,'class="image-$1 $2"') );

this works fine and outputs

<img src="" class="image-left smart" title="title for reference" />

but if i alter the html placing the class before the align I just get the original html string


You could use jQuery to do this.

var s = '<img src="" align="left" class="smart" title="title for reference" />';

$('<div/>').append(
    $(s).addClass('image-' + $(s).attr('align'))
        .removeAttr('align')
).html();

This has the advantage of not being dependant on particular ordering of attributes etc.. And you could of course, just add the modified HTML to the DOM tree instead of using the trick with the $('<div/>') to get the html text.


Regular expressions are notoriously bad at working with markup, because markup isn't regular. As you're working in a browser, you already have a powerful HTML parser at your disposal, so resorting to a regex isn't your best option.

As a'r suggests, this can be done easily enough with jQuery. Here's a pure-DOM equivalent:

var div = document.createElement("div");

div.innerHTML = s;

var img = div.firstChild;

img.className += " image-" + img.getAttribute("align");
img.removeAttribute("align");

console.log(div.innerHTML);

(Gecko DOM reference)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜