Reputation: 57
I have a code for displaying whole document in a HTML
<!DOCTYPE HTML>
<html>
<head>
<script>
let openFile = function(event) {
let input = event.target;
let reader = new FileReader();
reader.onload = function(){
let text = reader.result;
let node = document.getElementById('output');
node.innerText = text;
console.log(reader.result.substring(0, 200));
};
reader.readAsText(input.files[0]);
};
</script>
</head>
<body>
<input type='file' accept='text/plain' onchange='openFile(event)'><br>
<div id='output'>
</div>
</body>
</html>
I need to load a document then display only strings I need - names and url like:
Document example:
#NAME:Elis:
http://elis.com
#NAME:Emma:
http://emma.com
Display:
<a href=http://elis.com>Elis</a>
<a href=http://emma.com>Emma</a>
Upvotes: 0
Views: 306
Reputation: 33439
let openFile = function(event) {
let input = event.target;
let reader = new FileReader();
reader.onload = function() {
let text = reader.result;
let node = document.getElementById('output');
// node.innerText = text;
var resultText = "";
lines = reader.result.split(/\r\n|\r|\n/);
for (let i = 0; i < lines.length - 1; i += 2) {
var matches = lines[i].match(/\#NAME:([^:]+)/);
resultText += `<a href="${lines[i+1].trim()}">${matches[1].trim()}</a>\n`;
}
// innerText here only for demonstration purpose
// use innerHTML for working code instead
node.innerText = resultText;
// node.innerHTML = resultText
};
reader.readAsText(input.files[0]);
};
<input type='file' accept='text/plain' onchange='openFile(event)'><br>
<div id='output'>
Upvotes: 1
Reputation:
var str = `#NAME:Elis:
http://elis.com
#NAME:Emma:
http://emma.com`;
const makeUpHrefs = str => {
let arr = str.split(/\n#/);
arr = arr.map(row => '<a href="' + row.match(/\n(.*)/)[1] + '">' + row.match(/NAME:(.*?):/)[1] + '</a>');
return arr;
};
So, makeUpHrefs(str)
will return array of html's:
<a href="http://elis.com">Elis</a>
<a href="http://emma.com">Emma</a>
Upvotes: 0