Home > Software engineering >  Typescript div,br and   I don't want the tags to be displayed
Typescript div,br and   I don't want the tags to be displayed

Time:01-23

  const handleSettingRuleChange = (value?: any) => {
if (formState?.errors?.message) trigger('message')
setValue('message', value)
console.log('Greeting->'   defaultValues.message);
const vl: string = value.replace("<div>&nbsp;<br></div>", " ")
console.log('handleSettingRuleChange->'   vl)}

The output of this code is as follows. div br and   I don't want the tags to be displayed. Even though I replaced it, it didn't go away. how can i fix this

example log:

handleSettingRuleChange->alperen&nbsp;<div><br></div><div>kapusuz</div><div>dfasf</div><div>&nbsp;</div>

CodePudding user response:

It's not perfectly clear all the possibilities you may encounter in that input string so to make sure that it will always work returning exactly the text content, you may just create a temporary element and fill its innerHTML with that string so that when fetching its textContent you will be returned the exact text content as it would be when the html was rendered.

But since .textContent won't automatically count <br> elements as new lines, you may need to process the html element and all its children recursively and if any node found is of type BR just return a new line.

I edited the answer so that now it takes br into account:_

const input = 'alperen&nbsp;<div><br></div><div>kapusuz</div><div>dfasf</div><div>&nbsp;</div>';

console.log( returnTextContent(input) ); //alperen\NEWLINEkapusuzdfasf

//creates a temp div element with the given html as its content and returns its rendered text content
function returnTextContent(html){
  const tempContainer = document.createElement('div');  
  tempContainer.innerHTML = html;
  return getTextContent(tempContainer);  
}

//walks through node and its children to return its text content
function getTextContent(node){    
  //if node is of type <BR> returns newline
  if(node.tagName == 'BR')
    return "\n";
  //else if node has no children returns its .textContent
  if(node.childNodes.length == 0)
    return node.textContent;     
  //else return the concatenated text content of its children
  return [...node.childNodes].reduce(
    (textContent, child) => { return textContent  = getTextContent(child) }, "");  
}

CodePudding user response:

You are trying to replace exact string <div>&nbsp;<br></div>. Replace particular tags:

.replaceAll('<div>', ' ').replaceAll('</div>', ' ').replaceAll('<br>', ' ').replaceAll('&nbsp;', ' ');
  • Related