【问题标题】:Replace all <img> tag with img alt text将所有 <img> 标签替换为 img alt 文本
【发布时间】:2013-08-09 06:43:02
【问题描述】:

我知道如何在 php 中执行此操作,但我需要在 javascript/jquery 中执行此操作。

我正在尝试类似以下内容:

$('#NewBox').html( $('#OldBox').html().Replace('/<img(.*)alt="(.*)"\>/g', "$2") );

我不认为 javascript 有 preg_replace,我只知道 replace 方法。使用“g”应该用正则表达式的第二个参数(作为alt)替换所有实例。知道为什么这不起作用吗?

更新: (希望这能更好地理解我想要什么)

我有一个这样的字符串:

var str = 'This is a string with <img src="./images/logo.png" alt="logo" /> an image'

我想用 alt 替换该字符串中的所有标签,所以现在是:

'This is a string with logo an image'

【问题讨论】:

标签: javascript jquery


【解决方案1】:

Don't use regular expressions to manipulate HTML。使用 DOM。在处理客户端 JavaScript 时,这会加倍,因为编辑 HTML 可能会破坏事件处理程序绑定。

只需获取每个图像,遍历每个图像,然后替换为 alt 属性的值。

$('img').each(function () {
  $(this).replaceWith(
    $(this).attr('alt')
  );
});

【讨论】:

  • 可以说我有一个包含该文本的文本框。我将如何使用它来使用它?
【解决方案2】:

当您可以安全地使用解析工具时,您应该避免使用正则表达式。 jQuery 可以为您解析该 HTML。

var str = 'This is a string with <img src="./images/logo.png" alt="logo" /> an image';
console.log('input: '+str);

// first create an element and add the string as its HTML
var container = $('<div>').html(str);

// then use .replaceWith(function()) to modify the HTML structure
container.find('img').replaceWith(function() { return this.alt; })

// finally get the HTML back as string
var strAlt = container.html();
console.log('output: '+strAlt);

输出:

input: This is a string with <img src="./images/logo.png" alt="logo" /> an image
output: This is a string with logo an image 

demo fiddle

【讨论】:

  • 仍然无法正常工作,但无论如何感谢。我会接受这个作为答案。
  • 如果它不起作用,你根本不必接受它。它怎么不工作?你试过演示吗?如果您提供更多详细信息,我们可以为您提供进一步的帮助。