正则表达式不适用于javascript中的文本

时间:2017-02-05 10:44:03

标签: javascript regex html5-filesystem

<html>
<body>

<div id="inputTextToSave" cols="80" rows="25"></div>
<table>
    <tr><td>Text to Save:</td></tr>
    <tr>
        <td colspan="3">

        </td>
    </tr>
    <tr>
        <td>Filename to Save As:</td>
        <td><input id="inputFileNameToSaveAs"></input></td>
        <td><button onclick="saveTextAsFile()">Save Text to File</button></td>
    </tr>
    <tr>
        <td>Select a File to Load:</td>
        <td><input type="file" id="fileToLoad"></td>
        <td><button onclick="loadFileAsText()">Load Selected File</button><td>
    </tr>
</table>
<button onclick="myFunction()">Try it</button>

<script type="text/javascript">

function saveTextAsFile()
{
    var textToSave = document.getElementById("inputTextToSave").value;
    var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
    var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
    var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;

    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    downloadLink.href = textToSaveAsURL;
    downloadLink.onclick = destroyClickedElement;
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);

    downloadLink.click();
}

function destroyClickedElement(event)
{
    document.body.removeChild(event.target);
}

function loadFileAsText()
{
    var fileToLoad = document.getElementById("fileToLoad").files[0];

    var fileReader = new FileReader();
    fileReader.onload = function(fileLoadedEvent) 
    {
        var textFromFileLoaded = fileLoadedEvent.target.result;
        document.getElementById("inputTextToSave").value = textFromFileLoaded;
    };
    fileReader.readAsText(fileToLoad, "UTF-8");
}

function myFunction() {
    var str = document.getElementById("inputTextToSave").innerHTML; 
    var txt = str.replace(/uploads/g,"uploads1");
    document.getElementById("demo").innerHTML = txt;
}

</script>

</body>
</html>

此代码来自https://thiscouldbebetter.wordpress.com/2012/12/18/loading-editing-and-saving-a-text-file-in-html5-using-javascrip/

我为了替换div id inputTextToSave中的一些文本而编辑了一点。

每当我通过myFunction按钮致电Try it时。 div id="inputTextToSave"元素中没有发生字符串替换。

如何在文件中替换文本并将数据保存到新文件?

0 个答案:

没有答案