0

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:

'<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'.

xander17
  • 141
  • 9

3 Answers3

2

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>
Kinglish
  • 23,358
  • 3
  • 22
  • 43
1

Try

function getFirstNonBlankSubstring(text, separator) {
  const array = text.split(separator);
  for (const substring of array) {
    if (substring.trim()) {
      return substring;
    }
  }
}

getFirstNonBlankSubstring(element.innerHTML, '<br>') should give you what you need as long as you can count on the <br> tags looking exactly like that.

If you can't, you may need to walk the DOM to find text nodes.

JSmart523
  • 2,069
  • 1
  • 7
  • 17
  • It works exactly as expected but so is Kinglish answer and he was the first to answer so I accepted his answer. Thank you very much for taking the time to answer my question, I appreciate it. – xander17 Nov 30 '21 at 21:48
  • Array.prototype.map is not lazy, so Kinglish's answer will continue parsing the string after it's got what it needs. That said, if your innerHTML isn't huge and it's more understandable to you then I agree it's a better answer. – JSmart523 Nov 30 '21 at 21:55
0

You can doit like this

//get the text and remove white space from left
var readText = document.getElementById("content").textContent.trimLeft();

//How many splits you want out    
var freeSpaces = 3;
//
var splittext = readText.split(' ');
var newText = splittext.slice(0, freeSpaces);

//final text
var finalText = newText.join(' ');