替换<pre> tag with <br/> tag in javascript

时间:2017-07-10 15:16:49

标签: javascript html regex react-native

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, i.e 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.

2 个答案:

答案 0 :(得分:4)

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));

答案 1 :(得分:0)

这是一个简单的解决方案

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;
};