简体   繁体   中英

Replace all break lines present in <pre> tag with <br> tag in javascript

I have a html string like this

<div>
    <p>
        All set to go in.
        Finally in.
    </p>
    <pre>
        Yup this text is present 
        inside of the pre tag.
    </pre>
</div>

I want to replace line breaks presents inside pre tag with < br > tags.

Final result should be.

<div>
    <p>
        All set to go in.
        Finally in.
    </p>
    <pre>Yup this text is present<br> inside of the pre tag.</pre>
</div>

What I have tried so far? I tried to this with regex and created pattern which looks like this :- /is(?=.*<\\/pre>)/g which is only capable of finding 'is' which are before </pre> tag. I also want to include one more condition in this, ie it should if after <pre> tag. Try this regex at https://regex101.com/r/qW7tZ1/5

How do I replace all line breaks in a string with <br /> tags? doesn't fit my condition as I don't want to replace all occurrence of line break.

Don't use regex to parse/manipulate html, use simple DOM functions

 let html = `<div> <p> All set to go in. Finally in. </p> <pre> Yup this text is present inside of the pre tag. </pre> </div>`; function newlineToBr(str) { let div = document.createElement('div'); div.innerHTML = str; Array.from(div.getElementsByTagName('pre')).forEach(pre => { pre.innerHTML = pre.innerHTML.replace(/\\n/g, "<br />"); }); return div.innerHTML; } console.log(newlineToBr(html)); 

Here is a simple solution

export default (html: string): string => {
  if (html.indexOf('<pre>') === -1) return html;
  const array = html.split('<pre>');
  let finalContent = '';
  for (let i = 0; i < array.length; i++) {
    if (i === 0) {
      finalContent = `${array[0]}<pre>`;
    } else {
      const secondArray = array[i].split('</pre>');
      finalContent = `${finalContent}${secondArray[0]
        .replace(/\r\n/g, '<br />')
        .replace(/[\r\n]/g, '<br />')}</pre>${secondArray[1]}`;
      if (i !== array.length - 1) finalContent = `${finalContent}<pre>`;
    }
  }
  return finalContent;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM