假设字符串中有一个数字标签
const content = 'Here is a sentence followed up with <figure><img /></figure> plus some more text.'
是否有一种方法,我可以检查,看看是否有一个数字标签在字符串中,选择标签和它的所有内容,并删除或过滤掉所有与React或Javascript?
期望的输出将是
const content = 'Here is a sentence followed up with plus some more text.'
我知道它是不干净的,但它支持一个Algolia查询。
您可以使用RegEx。一个可能的RegEx是/(<figure>.+</figure>)/g
(https://regexr.com/6ke0o)
const content = 'Here is a sentence followed up with <figure><img /></figure> plus some more text.'.replace(/(<figure>.+</figure>)/g, '')
您可以使用DOM解析器,创建一个元素,将您的内容放入innerHTML中,并过滤childNodes,以便只保留文本节点。
const content = 'Here is a sentence followed up with <figure><img /></figure> plus some more text.'
const tester = document.createElement('div');
tester.innerHTML = content;
const output = [...tester.childNodes].filter(child => child.nodeType === 3).map(child => child.nodeValue.trim()).join(" ");
console.log(output);
如果你只想删除标签(不是标签主体):
console.log("Here is a sentence followed up with <figure><img /><figure> plus some more text.".replaceAll(/<\?[a-zA-Zs]+/?>/g,""))
或:
.replaceAll( /(<([^>]+)>)/ig, '');
如果你只想删除figure
标签:
console.log("Here is a sentence followed up with <figure><img/><figure> plus some more text.".replaceAll(/<figure>.+<figure>/g,""))