<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta charset="utf-8" /> <title>文本转代码拼接</title> </head> <body> 选择文本转代码拼接 <input type="file"/> <textarea style="height:80vh;width:100%;margin:1em 0;"></textarea> </body> </html>
document.querySelector("input").oninput = async function () { let file = this.files[0]; if (file) { let fr = new FileReader(); fr.onload = function (e) { let txt = e.target.result; let codes = text2code(txt); document.querySelector('textarea').value = codes.join('\n') } fr.readAsText(file); } } function text2code(text) { let result = []; let regex = /^( {4})+/; let lines = text.split('\n'); for (let line of lines) { let match = line.match(regex); if (match) { let leadingSpaces = match[0]; let numTabs = leadingSpaces.length / 4; let tabs = '\\t'.repeat(numTabs); line = line.replace(leadingSpaces, tabs); line = line.replace("'[", "\'[").replace("]'", "]\'"); } result.push(`codes.push('${line.trim()}');`); } return result; }