gpt4 book ai didi

javascript - 加载文件并解析文档

转载 作者:行者123 更新时间:2023-12-03 00:39:00 24 4
gpt4 key购买 nike

我有一个用于在 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>

我需要加载一个文档,然后仅显示我需要的字符串 - 名称和网址,例如:

文档示例:

#NAME:Elis:
http://elis.com
#NAME:Emma:
http://emma.com

显示:

<a href=http://elis.com>Elis</a>
<a href=http://emma.com>Emma</a>

最佳答案

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'>

关于javascript - 加载文件并解析文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53539500/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com