Javascript 是否可以使用Jquery保留img标记和其他标记的文本?
我有一个Html代码示例:Javascript 是否可以使用Jquery保留img标记和其他标记的文本?,javascript,html,jquery,Javascript,Html,Jquery,我有一个Html代码示例: <br>Hola<img class="emoji" src=".../_images/emoji/1F44B.png"><br><p class="MsoNormal">Adios.</p><p class="MsoNormal"><b>Si</b></p><img clas
<br>Hola<img class="emoji" src=".../_images/emoji/1F44B.png"><br><p class="MsoNormal">Adios.</p><p class="MsoNormal"><b>Si</b></p><img class="emoji" src=".../_images/emoji/1F4AA.png">
在没有任何积极结果的情况下,我试图做的是仅保留文本,但使用以下img标记:
Hola<img class="emoji" src=".../_images/emoji/1F44B.png">Adios.Si<img class="emoji" src=".../_images/emoji/1F4AA.png">
我需要一些想法或解决方案,这个字符串是动态的,如果我能保留br标记,那将是非常棒的,我尝试了很多事情但都没有成功。一个可能的解决方案,尽管我忍不住觉得它可以优化,如下所示:
// named function, declared using const and defined using
// Arrow function syntax; here the function receives two
// arguments, the 'haystack' a String of HTML that you want
// to process, and an Object to update the settings/behaviour:
const retainOnly = (haystack, opts) => {
// an Object that defines the default behaviour of the
// function:
// keep: an Array of element-names ('img','div','br'...)
// that you want to retain in the String, and
// keepText: a Boolean true/false; true if you wish to
// retain textNodes, false if you wish to remove
// them.
let settings = {
'keep': ['img'],
'keepText': true
},
// a <div> element in which to place the String of
// HTML, in order to use DOM methods rather than
// parsing HTML with regular expressions (see the
// bibliography):
temp = document.createElement('div');
// using Object.keys() to return an Array of the iterable
// keys of the opts Object, or an empty Object-literal,
// to update the default settings Object; we use
// Array.prototype.forEach() to iterate over the Array of
// keys, again using an Arrow function:
Object.keys(opts || {}).forEach(
// the 'key' is passed into the function, and is a
// reference to the current key of the Array of keys
// over which we're iterating; in the function we
// set the property-value of the key of the settings
// Object to the value held in the property-value of
// the opts Object:
(key) => settings[key] = opts[key]
);
// setting the innerHTML of the created <div>:
temp.innerHTML = haystack;
// caching the childNodes of the <div> as an Array of
// Nodes:
let children = [...temp.childNodes];
// here we use a for...of loop to iterate over the
// Array of childNodes in the 'children' variable:
for (let child of children) {
// if the child has a nodeType of 1 (and is therefore
// an HTMLElement, and the lower-cased tagName of that
// child is not included in the settings.keep Array:
if (child.nodeType === 1 && !settings.keep.includes(child.tagName.toLowerCase())) {
// we replace that childNode using the
// childNode.replaceWith() method, passing in
// that child's innerHTML as the String, and
// also the opts Object passed to this function:
child.replaceWith(retainOnly(child.innerHTML, opts));
}
// otherwise if the child's nodeType is equal to 3 and
// settings.keepText is equal to false (so we don't wish
// to retain textNodes):
else if (child.nodeType === 3 && settings.keepText === false) {
// we use parentNode.removeChild() to remove that child:
child.parentNode.removeChild(child);
}
}
// once that processing is completed we return the
// temp.innerHTML String to the calling context
// (returning the innerHTML is also how the recursion
// works in this function):
return temp.innerHTML;
};
// your string of HTML defined as a template-literal:
let HTMLString = `<br>Hola<img class="emoji" src=".../_images/emoji/1F44B.png"><br><p class="MsoNormal">Adios.</p><p class="MsoNormal"><b>Si</b></p><img class="emoji" src=".../_images/emoji/1F4AA.png">`,
// caching the result of calling the function:
processed = retainOnly(HTMLString);
// outputting the processed HTMLString to the console:
console.log(processed)
// 'Hola<img class="emoji" src=".../_images/emoji/1F44B.png">Adios.Si<img class="emoji" src=".../_images/emoji/1F4AA.png">'
const retainOnly=haystack,opts=>{
让设置={
“保留”:[“img”],
“keepText”:true
},
temp=document.createElement'div';
Object.keysopts | |{}.forEach
key=>settings[key]=opts[key]
;
temp.innerHTML=干草堆;
让子节点=[…临时子节点];
让孩子的孩子{
如果child.nodeType===1&&!settings.keep.includeschild.tagName.toLowerCase{
child.replaceWithretainOnlychild.innerHTML,选项;
}
如果child.nodeType==3&&settings.keepText==false{
child.parentNode.removeChildchild;
}
}
返回temp.innerHTML;
};
让HTMLString=`HolaAdios.
Si
`; let processed=retainOnlyHTMLString;console.logprocessed您可以使用正则表达式将字符串拆分为仅包含文本和图像部分的数组,然后加入结果数组,如下所示: const removeTags=html=>html.split/]*>/.join; const testString='Hola
Adios.
Si
'; const result=removeTagstestString; 这里的神奇之处在于removeTags函数中的正则表达式]*>,在该函数中,我们选择了括在小于或大于括号中的所有文本,但标记以img开头的情况除外 片段: const removeTags=html=>html.split/]*>/.join; const testString='HolaAdios.
Si
'; const result=removeTagstestString; document.getElementById'finalResult'.innerText=result; p{font-family:sans-serif}pre{背景色:eee;填充:5px;边框半径:4px;空白:pre-line} 首字母: 结果:你能展示你最好的尝试吗?这样,我们可能会告诉您哪里出了问题,这样您就可以从失败中学习,也可以从我们展示并与您共享的工作代码中学习。将所有图像放到数组中,替换为类似[IMG1],do.text,将[IMG1]替换回实际图像是否可以将br标记也保留在该拆分中?@J.Mo-yep,只需将一个管道br添加到负前瞻中,就可以了:removeTags=html=>html.split/]*>/.join@我很高兴能帮上忙!