javascript .replace width tag

javascript .replace width tag

本文关键字:tag width replace javascript      更新时间:2023-09-26

正在寻找javascript reg ex替换的帮助。我需要的是替换的所有实例

width="100">

style="width: 100px;"

但实际的px值是可变的,这就是给我带来问题的原因。我知道reg表达式是可行的,但我不太理解。

这是一个类似的问题,但对我来说并不能解决问题:JavaScript Regex替换宽度属性匹配

这是一个问题的原因是因为TinyMce生成的HTML。。。

两个选项:

  • 使用正则表达式

  • 解析HTML并使用DOM(首选)

使用正则表达式

表达式相当简单:

str = str.replace(/'bwidth="('d+)"/g, 'style="width: $1px"');

替换字符串中的$1填充有第一捕获组的内容。

示例:

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, "&amp;")
      .replace(/</g, "&lt;") +
    "</p>"
  );
}

但请注意,这将:

  1. 替换字符串中所有处的width="nnn",即使不在起始标记内

  2. 最终为已经有一个的标签添加第二个style属性

如果可以的话,那太好了;如果没有,您可能需要解析HTML,处理解析后的DOM节点,然后再次序列化它。

解析HTML并使用DOM

更好的选择是解析HTML并使用DOM。您已经说过HTML将用于div,所以我们不必担心独立的表单元格等问题。

下面是一个简单的解析和更新示例:

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) { // An 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, "&amp;")
    .replace(/</g, "&lt;") +
    "</p>"
  );
}

我的第一个想法也是使用DOM,而不是使用RegEx。我们可以使用支持属性选择器的querySelector,而不是对所有元素进行迭代。

var html = '<img src="//placehold.it/100x100" alt="" style="100px;">'+
           '<img src="//placehold.it/120x120" alt="" width="120" style="border: 2px solid steelblue;">'+
           '<img src="//placehold.it/140x140" alt="" width="140">',
    wrap = document.createElement('div'),
    nodes;
wrap.innerHTML = html;
nodes = wrap.querySelectorAll('[width]');
Array.prototype.forEach.call(nodes, function(el) {
    var width = el.getAttribute('width');
    if(width) {
        el.removeAttribute('width');
        el.style.width = width+'px';
    }
});