Peter Pik
Peter Pik

Reputation: 11193

remove strong tag and its content from string

I'm having below string with this html, i'm wondering how can i remove/filter all strong tags and its text from the string?

html

<p>
    <br>
    2-3 spsk græsk yoghurt, gerne 10 % 
    <strong>Dressing: </strong>
    <br>
    1 lille spsk god mayonnaise
    <br>
    1-2 tsk æbleeddike 
    <br>
    1-2 tsk honning 
    <br>
    himalayasalt og friskkværnet hvid peber
    <br>
</p>

so far i have this, but only seem to remove strong tag if it is at the top

var ingredientsArray = ingredients.split('<br>').map(it => it.trim()).filter(it => !!it && !it.startsWith('<strong>'));

Upvotes: 0

Views: 1420

Answers (4)

user663031
user663031

Reputation:

Rather than trying to manipulate the string, apply a CSS rule to wherever this is going to be put into the DOM:

strong { display: none; }

Upvotes: 0

jcubic
jcubic

Reputation: 66590

You can use regex for this:

var ingredientsArray = ingredients.replace(/<strong>[\s\S]*?<\/strong>/g, '')
     .split('<br>').map(it => it.trim()).filter(Boolean);

Upvotes: -1

adeneo
adeneo

Reputation: 318312

Parsing the string as HTML would most likely be the way to go, depending on what the goal is ?

var ingredients = '<p><br>2-3 spsk græsk yoghurt, gerne 10 % <strong>Dressing: </strong><br>1 lille spsk god mayonnaise<br>1-2 tsk æbleeddike <br>1-2 tsk honning <br>himalayasalt og friskkværnet hvid peber<br></p>';

var doc = new DOMParser().parseFromString(ingredients, 'text/html');

[].forEach.call(doc.querySelectorAll('strong'), function (item) {
    item.parentNode.removeChild(item);
});

document.body.innerText = '<pre>' + doc.body.innerHTML + '</pre>';

Upvotes: 2

trincot
trincot

Reputation: 350841

You can use the DOM API for this:

function stripStrong(html) {
    var span = document.createElement('span');
    span.innerHTML = html;
    [...span.getElementsByTagName('strong')].reverse().forEach( 
        strong => strong.parentNode.removeChild(strong)
    );
    return span.innerHTML;
}

var html = `<p>
    <br>
    2-3 spsk græsk yoghurt, gerne 10 % 
    <strong>Dressing: </strong>
    <br>
    1 lille spsk god mayonnaise
    <br>
    1-2 tsk æbleeddike 
    <br>
    1-2 tsk honning 
    <br>
    himalayasalt og friskkværnet hvid peber
    <br>
</p>`;

console.log(stripStrong(html));

Note that this also works if the strong tag has attributes, styles, is nested with other strong tags, etc... something that regular expressions can have trouble with.

Upvotes: 2

Related Questions