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

I want to remove all but a specific string in a JavaScript regular expression

There is a string like this

var string =
`<!-- paragraph {"className":"123"} -->
<p>abc</p>
<!-- /paragraph -->
 
<!-- paragraph {"className":"456"} -->
<p>cde</p>
<!-- /paragraph -->
 
<!-- paragraph {"className":"789"} -->
<p>fgh</p>
<!-- /paragraph -->`
 
const regex = /"className":"(.+)"/g;
string=string.replace(regex, '');
console.log(string);

I want to delete all characters except those following the className.

In other words, I want to make it look like 123456789 in the end.

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

If you can tell me a better way, I would appreciate your advice.

Any method other than replace is fine.

>Solution :

Use match then replace the string you don’t want

var string =
`<!-- paragraph {"className":"123"} -->
<p>abc</p>
<!-- /paragraph -->
 
<!-- paragraph {"className":"456"} -->
<p>cde</p>
<!-- /paragraph -->
 
<!-- paragraph {"className":"789"} -->
<p>fgh</p>
<!-- /paragraph -->`
 
const regex = /"className":"(.+)"/g;
let arr = string.match(regex, '');
arr = arr.map(e => e.replace(`"className":"`, '').slice(0, -1))
let str = arr.join('')
console.log(str);
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