我知道如何在PHP中执行此操作,但我需要在javascript/jquery中完成此操作.
我正在尝试以下内容:
$('#NewBox').html( $('#OldBox').html().Replace('/<img(.*)alt="(.*)"\>/g', "$2") );
Run Code Online (Sandbox Code Playgroud)
我不认为javascript有preg_replace,我所知道的是替换方法.使用"g"应该用正则表达式中的第二个参数替换所有实例(是alt).知道为什么这不起作用吗?
更新:(希望这更好地了解我想要的)
我有一个这样的字符串:
var str = 'This is a string with <img src="./images/logo.png" alt="logo" /> an image'
Run Code Online (Sandbox Code Playgroud)
我想用alt替换该字符串中的所有标签,所以它现在是:
'This is a string with logo an image'
Run Code Online (Sandbox Code Playgroud)
不要使用正则表达式来操纵HTML.使用DOM.在客户端JavaScript处理时,这会加倍,因为编辑HTML会破坏事件处理程序绑定.
只需获取每个图像,遍历每个图像,然后替换为alt属性的值.
$('img').each(function () {
$(this).replaceWith(
$(this).attr('alt')
);
});
Run Code Online (Sandbox Code Playgroud)