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

Remove unwanted matching text from string and get required value using js

I have string it contain unwanted html tags and text, so I want to remove unwanted matching text and get my required values:

Code:

var mystring = "<!-- html-text: 143 --> value 1  <!-- /html-text --><!-- html-text: 144 --> | <!-- /html-text --><!-- react-text: 145 --> value 3 <!-- /html-text --><!-- html-text: 146 -->, <!-- /html-text --><!-- html-text: 147 --> value 2 <!-- /html-text --><!-- html-text: 148 --> <!-- /html-text --><!-- html-text: 149 -->value 4 <!-- /html-text -->";
mystring = mystring.replace('<!-- html-text: 143 -->','');

console.log('str'+mystring);

Required output:

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

value 1  value 2 value 3 value 4

>Solution :

You can do this with regex:

var mystring = "<!-- html-text: 143 --> value 1  <!-- /html-text --><!-- html-text: 144 --> | <!-- /html-text --><!-- react-text: 145 --> value 3 <!-- /html-text --><!-- html-text: 146 -->, <!-- /html-text --><!-- html-text: 147 --> value 2 <!-- /html-text --><!-- html-text: 148 --> <!-- /html-text --><!-- html-text: 149 -->value 4 <!-- /html-text -->";
mystring = mystring.replace(/<!--.*?-->/g,'');

console.log(mystring);

Regex explanation:

  1. <!--...--> Marks the opening and ending of an HTML comment
  2. .* Matches any character zero or more times
  3. ? Remove "greedy matching" (match the least possible instead of most)
  4. g Global, meaning to replace all occurrences instead of just one
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