Home > OS >  Is there any way to remove the "Code Snippet" from a string?
Is there any way to remove the "Code Snippet" from a string?

Time:04-27

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.

CodePudding user response:

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, '')

CodePudding user response:

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);

CodePudding user response:

Here I'm assuming you can have multiple tags in content string. This will take care of all of those tags and return only text string.

If you're only going to have figure tags then I'd suggest to go with a simple regular expression mentioned in other answers.

```
import { parse } from "node-html-parser";

 const content =
      "Here is a sentence followed up with <figure><img /></figure> plus some more text.";
    const root = parse(content);

    let edited = "";

    root.childNodes.map((node) => (edited  = node.rawText));

    edited = edited.replace(/   /g, " ");
    console.log(edited);



```

CodePudding user response:

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,""))

  • Related