全部替换< img>标签与img替代文字 [英] Replace all <img> tag with img alt text
问题描述
我知道如何在php中执行此操作,但我需要在javascript / jquery中完成此操作。
I know how to do this in php, but I need this to be done in javascript/jquery.
我正在尝试以下内容:
$('#NewBox').html( $('#OldBox').html().Replace('/<img(.*)alt="(.*)"\>/g', "$2") );
我认为javascript没有preg_replace,我所知道的是替换方法。使用g应该用正则表达式中的第二个参数替换所有实例(是alt)。知道为什么这不起作用吗?
I don't think javascript has a preg_replace, and all I know of is the replace method. using "g" should replace all instances with the 2nd parameter from the regex (being alt). Any idea why this isn't working?
更新:
(希望这能更好地理解我想要的东西)
UPDATE: (hopefully this better understands what I want)
我有一个这样的字符串:
I have a string such as this:
var str = 'This is a string with <img src="./images/logo.png" alt="logo" /> an image'
我想用alt替换该字符串中的所有标签,所以它现在是:
I want to replace all tags inside of that string with the alt so it's now:
'This is a string with logo an image'
推荐答案
当您可以安全地使用解析工具时,应该避免使用正则表达式。 jQuery可以为你解析HTML。
You should avoid regexes when you can safely work with a parsing tool. jQuery can parse that HTML for you.
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
参见演示小提琴。
这篇关于全部替换< img>标签与img替代文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!