0

I'm trying to create a script which should remove some text from a file with node.js.

I have this file:

bla bla 
bla bla
<script>
   this text should be
   removed.
export default {
  some stuff here
}
</script>

I just want to remove all the text between <script> and export default {.

Note: I want to keep both <script> and export default }

2
  • So do you want the valid script to be there and remove invalid data from script tag? Is the export default { will be always there? Commented May 9, 2017 at 18:09
  • I just want to remove everything between <script> and export regardless the correctness of the code. I've seen node.js has a truncate function but I don't know if I'm able to use it in this case. Commented May 9, 2017 at 18:14

3 Answers 3

2

Regular expression works well

str = str.replace(/(.*\<script\>).*(export.*)/,  '$1$2');

Note:- Read file as a string, synchronously if its big.

Sign up to request clarification or add additional context in comments.

Comments

1

A simple regex matching should suffice:

const content = `blah blah
blah blah
<script>
   this text should be
   removed.
export default {
  some stuff here
}
</script>`;

content.replace(/\<script\>([\s\S]*)export/g, '<script>export');

Comments

0
var lineReader = require('readline').createInterface({
    input: require('fs').createReadStream('test_input.txt')
});

const start_marker = '<script>';
const end_marker = 'export default';
var deleteEnabled = false;

lineReader.on('line', function(line) {
    if (!deleteEnabled && line.startsWith(start_marker)) {
        console.log(line);
        deleteEnabled = true;
    } else if (deleteEnabled && line.startsWith(end_marker)) {
        deleteEnabled = false;
    }

    if (!deleteEnabled) {
        console.log(line);
    }
});

This will start deleting lines when the start_marker is hit, and stop deleting when the end_marker is hit.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.