简体   繁体   中英

How to remove inner text of HTML tag with HTML tag from a string using regex?

My String is given below ,

var str = "The test <del> SString </del> string , The other <del>textt </del> test&nbsp; string, <br/>  show &nbsp; something";

I can write regex pattern which is removed only html tag , pattern is given below,

pattern = /(<([^>]+)>)/ig 

In Str Variable, there can be any html tag like as bold tag(b), italic tag(i).... etc.

How to write regex pattern in jquery or javascript which will be remove inner text of html tag with html tag.

Actually the result will be,

"The test string , the other test string , show something"

Make it Lazy

<([^>]+)>.*?<\/\1>|<.*?\/>

Here is demo

sample code:

var re = /<([^>]+)>.*?<\/\1>|<.*?\/>/g;
var str = 'The test <del> SString </del> string , The other <del>textt </del> test&nbsp; string, <br/> show $nbsp; something\n\nThe test string , the other test string , show something';

var result = str.replace(re, '');

EDIT

Note: The above regex does not support tags having attributes.

Try below regex to cover any attributes having in tag. Here is the DEMO

<([^( |>)]+)([^>]*)>.*?<\/\1>|<.*?\/>

This would work.

var str = "The test <del> SString </del> string , The other <del>textt </del> test&nbsp; string, <br/>  show $nbsp; something";
$a = $('<div>'+str+'</div>');
$a.children().remove()
var whatYouWant = $a.text();

Following Function will help you,

function getChildText(node) {
    var text = "";
    for (var child = node.firstChild; !! child; child = child.nextSibling) {
        if (child.nodeType === 3) {
            text += child.nodeValue;
        }
    }
    return text;
}

Demo

var str = "The test <del> SString </del> string , The other <del>textt </del> test&nbsp; string, <br/>  show $nbsp; something";

What you want

$("<div>"+str+"</div>").text()
//result retun is: "The test  SString  string , The other textt  test  string,   show $nbsp; something"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM