html - javascript .replace width tag -
looking help javascript reg ex replacement. need, replace instances of
width="100">
with
style="width: 100px;"
but actual px value variable causing issues me. know reg look way go dont quite understand it.
this similar question doesn't solve issue me: javascript regex replace width attribute matching
the reason problem because of html generated tinymce...
two options:
using regular expression
parsing html , working dom (preferred)
using regular expressionthe look straightforward:
str = str.replace(/\bwidth="(\d+)"/g, 'style="width: $1px"');
the $1
in replacement string filled in content of first capture group.
example:
class="snippet-code-js lang-js prettyprint-override">var str = '<div width="100">stuff here</div><div width="240">more stuff here</div>'; display("before: '" + str + "'"); str = str.replace(/\bwidth="(\d+)"/g, 'style="width: $1px"'); display("after: '" + str + "'"); function display(msg) { document.body.insertadjacenthtml( "beforeend", "<p>" + string(msg) .replace(/&/g, "&") .replace(/</g, "<") + "</p>" ); }
but note that will:
replace width="nnn"
everywhere in string, if not within start tag
end adding sec style
attribute tag has one
if that's okay, great; if not, might want parse html, process resulting parsed dom nodes, , serialize again.
parsing html , working doma improve alternative parse html , work dom. you've said html div
, don't have worry things standalone table cells, etc.
here's simple parsing , updating example:
class="snippet-code-js lang-js prettyprint-override">var str = '<div width="100">stuff here</div><div width="240">more stuff here</div>'; var div = document.createelement('div'); div.innerhtml = str; update(div.childnodes); display("before: '" + str + "'"); str = div.innerhtml; display("after: '" + str + "'"); function update(nodes) { array.prototype.foreach.call(nodes, function(node) { var width; if (node.nodetype === 1) { // element width = node.getattribute("width"); if (width) { node.removeattribute("width"); node.style.width = width + "px"; } update(node.childnodes); } }); } function display(msg) { document.body.insertadjacenthtml( "beforeend", "<p>" + string(msg) .replace(/&/g, "&") .replace(/</g, "<") + "</p>" ); }
javascript html regex
No comments:
Post a Comment