Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

javascript - Is there a way to import a text file and display it onto the webpage but also make specific changes to each line on the text file?

I want to import a text file (not user import), for example:

Coding

There are several languages...

When the file is read, the first line should be in larger font and bolded, and the other lines can be kept in the text file format. I'm not sure if Javascript or something similar would work in HTML.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can simply modify the content from the file using RegEx and/or String.replace() to manipulate as needed.

A basic, rudimentary demo:

const process = () => {
  // some file content with line breaks
  const fileContent = 'line 1
line 2
line 3';

  const contentEditor = document.querySelector('#content');

  // very basic example of processing:
  // grab the first line using a regex
  let re = /(.*)
/mi;
  // replace the matching with new surrounding content
  let edited = fileContent.replace(re, '<h1><b>$1</b></h1>
');

  // replace breaks with <p>
  re = /
(.*)/gim;
  edited = edited.replace(re, '<p>$1</p>');

  // display
  contentEditor.innerHTML = edited;

  console.info(edited);
}

window.addEventListener('load', process, false);
#content {
  min-height: 50vh;
  background: AliceBlue;
}
<div id="content"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...