Skip to content Skip to sidebar Skip to footer

Regular Expression To Remove Text Outside The Tags In A String

Here is my string. Which will contain XML string Like below var str= 'rvrvrvrvvrvvvrvrvrtvrvr'; How can I remov

Solution 1:

Assuming your problem is only removing text not enclosed inside an element (and remaining code is well formed so you haven't strings like

var str= "<str>lorem <b>ipsum</str>";

) you could use a regular expression like this

var str= "<str>rvrv</str>rvrv<q1>vrvv</q1>vrvrv<q2>rtvrvr</q2>",
    elements = str.match(/<(.+?)>[^<]+<\/\1>/gi);

console.log(elements.join(''));

and this returns

<str>rvrv</str><q1>vrvv</q1><q2>rtvrvr</q2>

Note: to detect closing tags I used a backreference (see http://www.regular-expressions.info/brackets.html)

Post a Comment for "Regular Expression To Remove Text Outside The Tags In A String"