Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Merge JS Replace function into one line of code

I want to concatenate three replace Regex code into one.
In the following example I have remove DIV, I, IMG tags from title. It’s a expected behavior. The only problem with concatenation.

Anyone help me achieve this.

text = $('.text').attr('title')
//console.log(text)
bind = text.replace(/<(span|i)[^>]*>.*?<\/\1>/g, '').replace(/<img[^>]*>/g, '').replace(/<\/?div[^>]*>/g, '')
console.log(bind)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div title="Lorem Ipsum<div><img src='test.png'><i class='fa fa-check'></i></div>" class="text">Lorem Ipsum has been the industry's standard</div>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Parsing HTML with RegExp is probably a bad idea and will result in a brittle solution.

Why not just parse with DOMParser instead and then ask the resulting document for its innerText?

const attribString = "Lorem Ipsum<div><img src='test.png'><i class='fa fa-check'></i></div>";
const dp = new DOMParser();
const doc = dp.parseFromString(attribString, "text/html");
const text = doc.documentElement.innerText;
console.log(text);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading