Let's say I have figure tags in a string
const content = 'Here is a sentence followed up with <figure><img /></figure> plus some more text.'
Is there a way I can check to see if there is a figure tag in the string, select the tags and all of its contents, and remove or filter out all of them with React or Javascript?
The desired output would be
const content = 'Here is a sentence followed up with plus some more text.'
I know it is not clean but it supports an Algolia query.
You can use RegEx for this. One possible RegEx would be /(<figure>.+<\/figure>)/g (https://regexr.com/6ke0o)
So some sample code would look like this:
const content = 'Here is a sentence followed up with <figure><img /></figure> plus some more text.'.replace(/(<figure>.+<\/figure>)/g, '')
if you only want to remove tags (NOT tag body):
console.log("Here is a sentence followed up with <figure><img /><\figure> plus some more text.".replaceAll(/<\\?[a-zA-Z\s]+\/?>/g,""))
or:
.replaceAll( /(<([^>]+)>)/ig, '');
if you want to just remove figure tag:
console.log("Here is a sentence followed up with <figure><img/><\figure> plus some more text.".replaceAll(/<figure>.+<\figure>/g,""))
You could use the DOM parser, create an element, put your content in as innerHTML, and filter the childNodes so that only text nodes remain.
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);