views:

89

answers:

5

Hi.

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 start:

html = html.replace(/ style="width:\?([0-9])px*"/g, "width=\"$1\"");

Can anyone help me?

THANKS

A: 

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.

eWolf
+2  A: 
  1. It's generally considered a Bad Thing to do HTML parsing with RegExs.

    Why not edit the DOM from JavaScript?

  2. I'm not an expert on CSS, but isn't using style a better idea than width/height attributes?

  3. You forgot the whitespace after : (\s*). You don't want ? there since it will miss >1 space or a tab

DVK
thanks for the link, I will read it!
Juri
@Juri - just in case it's not obvious, the link is to the blog of one of two founders of StackOverflow.
DVK
A: 

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

Shiftbit
this is it, thanks!html = html.replace(/ style=".*?width:\s?(\d+).*?height:\s?(\d+).*?"/g, " width=\"$1\" height=\"$2\"");
Juri
Thanks Juri, glade you liked it!
Shiftbit
A: 

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 :-)

Juri
+1  A: 
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 ;-)

Álvaro G. Vicario
Thanks. I will test your code!
Juri
it's HTML-Code given from a WYSIWYG-Editor
Juri