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

Extract the first occurence from a string

I have a div with a contentEditable attribute and I struggle to extract the first text occurence from a string.

I am using innerHTML to get the text from it( I need to use it, can not use innerText or textContent) and it comes with a lot of <br>.

The string will be something like this:

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

<br> This is some text <br> <br> Another piece of text’. I need only the text(‘This is some text‘) without <br>.

The string will always have <br> in it and the place of the <br> may vary.

I tried using the replaceAll('<br>', '') and it returns 'This is some text Another piece of text' but I need only the first occurence 'This is some text'.

>Solution :

You can use string.split() to divvy up the content by <br>, then run that through a simple filter that will remove any empty items in the array, and finally choose the first item in the array, which will be the text you want.

let fragment = document.querySelector('div.content').innerHTML.split('<br>').filter(a => a.trim())[0].trim() ;
console.log(fragment);
<div class='content'>
<br> 
<br> <br> 
This is some text <br> 
<br>
<br> This is some more text <br> 
</div>
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