JavaScript实现HTML转Word:自定义文件名拼接问题求助
Hey there! The issue here is that you're using concat() incorrectly—it's not a global function for string concatenation in JavaScript. Let me break down the fix for you:
What Went Wrong
concat() is a method for arrays (to merge arrays) or individual strings (e.g., str.concat(otherStr)), but you're trying to use it as a standalone function with multiple string arguments. That's why your filename isn't generating properly.
Solution 1: Use String Concatenation with +
Replace your problematic line with this straightforward string拼接 using the + operator:
fileDownload.download = fname + '-' + name + '-LM-' + company + '.doc';
Solution 2: Use ES6 Template Literals (Cleaner Option)
For more readable code, use template literals (backticks `) which let you embed variables directly into the string:
fileDownload.download = `${fname}-${name}-LM-${company}.doc`;
Optional: Handle Empty Values
To avoid weird filenames if fname or name is empty, add quick checks to set fallback values:
// Trim whitespace and set defaults if values are empty const safeFname = fname.trim() || 'FirstName'; const safeName = name.trim() || 'LastName'; // Then use the safe values in your filename fileDownload.download = `${safeFname}-${safeName}-LM-${company}.doc`;
Full Modified Code
Here's your complete script with the template literal fix applied:
<script> // SAVE AS WORD var fname = document.getElementsByName("fname")[0].value; var name = document.getElementsByName("name")[0].value; var company = <?php echo json_encode($company); ?>; function exportHTML(){ var header = "<html xmlns:o='urn:schemas-microsoft-com:office:office' " + "xmlns:w='urn:schemas-microsoft-com:office:word' " + "xmlns='http://www.w3.org/TR/REC-html40'>" + "<head><meta charset='utf-8'><title>Export HTML to Word Document with JavaScript</title></head><body>"; var footer = "</body></html>"; var sourceHTML = header + document.getElementById("pdf").innerHTML + footer; var source = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(sourceHTML); var fileDownload = document.createElement("a"); document.body.appendChild(fileDownload); fileDownload.href = source; // Fixed filename using template literals fileDownload.download = `${fname}-${name}-LM-${company}.doc`; fileDownload.click(); document.body.removeChild(fileDownload); } </script>
This should correctly generate your custom filename when saving the Word document. Let me know if you run into any other issues!
内容的提问来源于stack exchange,提问作者Hymed Ghenai

