JavaScript String Replace with a tricky regular expression
I'm trying to work out what regular expression I would need to change this string
html = '<img style="width: 311px; height: 376px;" alt="test" src="/img/1268749322.jpg" />';
to this
html = '<img width="311" height="376" alt="test" src="/img/1268749322.jpg" />';
with the help of Javascript.replace.
This is my st开发者_如何学Cart:
html = html.replace(/ style="width:\?([0-9])px*"/g, "width=\"$1\"");
Can anyone help me?
THANKS
It's generally considered a Bad Thing to do HTML parsing with RegExs.
Why not edit the DOM from JavaScript?
I'm not an expert on CSS, but isn't using style a better idea than width/height attributes?
You forgot the whitespace after
:
(\s*
). You don't want ? there since it will miss >1 space or a tab
html = '<img style="width: 311px; height: 376px;" alt="test" src="/img/1268749322.jpg" />';
var d = document.createElement("div");
d.innerHTML = html;
var img = d.firstChild;
var width = parseInt(img.style.width, 10);
var height = parseInt(img.style.height, 10);
img.setAttribute("width", width);
img.setAttribute("height", height);
img.removeAttribute("style");
alert(d.innerHTML);
Of course, things get slightly easier if you don't start with a string ;-)
Gumbo is right, you should use DOM.
But to your regex: What is \?
(question mark) supposed to mean? I would insert \s*
(any number of whitespaces) at that position.
Yeah, normally I would do it with DOM, but in this special case I need to parse HTML-Code given from a WYSIWYG-Editor whish filters style-attributes. In general this is good, but for the pictures I would like to keep the set sizes with this html.replace-Hack.
This is the answer:
html = html.replace(/ style=".*?width:\s?(\d+).*?height:\s?(\d+).*?"/g, " width=\"$1\" height=\"$2\"");
Thanks for your help :-)
I can make it more elaborate if you wish, let me know how this works:
html = html.replace(/style=".*?width:\s?(\d+).*?height:\s?(\d+).*?"/g, "width=\"$1\" height=\"$2\"");
Edit: escaped qq
精彩评论