You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript实现HTML转Word:自定义文件名拼接问题求助

Fix for Custom Filename When Saving Word Files with JavaScript

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 13:37:42