2

I am using code from JavaScript: Create and save file to save a string to a text file

var searchReplace = search.toString().replace(/":1200"/gi, /\n/);// replace a patturn with another patturn /gi is all instances /gi is non-case-sensitive 

    // Function to download data to a file, ref: https://stackoverflow.com/questions/13405129/javascript-create-and-save-file
    function saveData(data, filename, type) {
        var file = new Blob([data], { type: type });
        if (window.navigator.msSaveOrOpenBlob) // IE10+
            window.navigator.msSaveOrOpenBlob(file, filename);
        else { // Others
            var a = document.createElement("a"),
                url = URL.createObjectURL(file);
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            setTimeout(function () {
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);
            }, 0);
        }
    }
    saveData(searchReplace, "output.txt", Text); //calls the save file function
  • search is a string containing various text with no whitespace

Currently the text file stores the string on a single line and I would like to know how to change it to recognize certain characters as new lines or carriage returns like \n or \r

Less importantly, I would if its not too significant, like to know how to have the function update the text file if its exists rather than adding output(1).txt etc

  • 1
    `data = data.replace(/pattern/g, '\n')` Replace `pattern` with the string you want to replace with newline. – Barmar Jan 30 '20 at 23:10
  • I probably should have mentioned but I already tried data.replace before running this download function almost exactly as you mentioned and I can definitely replace a pattern with a \n for example but when the download function runs it still saves a text file as a single line but now with \n in the line, it seems the download function needs to change to recognize the \n or other pattern in some way – Nigel McDonald Jan 30 '20 at 23:56
  • I can't think of any reason why it would change `\n` to literal backslash and n. You should show the code that you tried. – Barmar Jan 31 '20 at 00:48
  • I have added the exact code I am using and as mentioned search is a string containing text with no whitespaces which is why I would like to insert returns or the like – Nigel McDonald Jan 31 '20 at 03:04
  • 1
    The second argument to `replace` should be a string, not a regexp. `var searchReplace = search.toString().replace(/":1200"/gi, '\n');` – Barmar Jan 31 '20 at 03:08
  • Is it difficult to have the save function append output.txt rather than create a new file each time? – Nigel McDonald Jan 31 '20 at 03:52
  • I think you need to let the user select the file with a file dialogue. If they select an existing file it will ask them if they want to overwrite it. – Barmar Jan 31 '20 at 16:29

0 Answers0