<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>
我为了替换div id inputTextToSave中的一些文本而编辑了一点。
每当我通过myFunction
按钮致电Try it
时。 div id="inputTextToSave"
元素中没有发生字符串替换。
如何在文件中替换文本并将数据保存到新文件?