user12499672
user12499672

Reputation: 35

Trying to do "empty" string checks and I cannot figure it out

I'm trying to make a automated file modifying script for some reason and I am stuck on something..

I have source code below:

const fs = require('fs');
var str = fs.readFileSync("./premaplist.txt");
str = str.toString().split("\n");
var result = "";
str.forEach(s => {
    var addstr = s;
    if(!s.includes("[")) {
        if(s.replace(/[.YBPOKGR#]/g, "") == s)return;
        addstr = "##########";
    }
    result += addstr+'\n';
})
// fs.writeFileSync("./premaplist.txt", result);
console.log(result);

So, the result I expect is let empty string AND string that includes [ alone and change others to ##########, but it replaces a empty string as ########## too.

Is the text file being special? or am I doing it wrong or missing something?

Input:

[image#1]
.....B....
..BB..BBB.
.BBBBBBB.B
BBBBBBBBB.
##########

[image#2]
GGGG......
GGGGGG....
GGGGGGG...
GGGGGGG...
GGGGGGGG..
GGGGGGGG..
GGGGGGGG..
GGGGGGGGG.
GGGGGGGGG.

[image#3]
.........K

(there are actually thousands of these)

Expected output:

[image#1]
##########
##########
##########
##########
##########

[image#2]
##########
##########
##########
##########
##########
##########
##########
##########
##########

[image#3]
##########

Actual output:

[image#1]
##########
##########
##########
##########
##########
##########
[image#2]
##########
##########
##########
##########
##########
##########
##########
##########
##########
##########
[image#3]
##########

Upvotes: 1

Views: 52

Answers (1)

M A Salman
M A Salman

Reputation: 3820

The output you are getting because you are doing return when its empty string therefore nothing gets added to result when its empty string

Try doing like this

const fs = require('fs');
var str = fs.readFileSync("./premaplist.txt");
str = str.toString().split("\n");
var result = "";
str.forEach(s => {
    var addstr = s;
    if(!s.includes("[")) {
        addstr = s.replace(/[.YBPOKGR#]/g, "") == s ?"":"##########"
    }
    result += addstr+'\n';
})
// fs.writeFileSync("./premaplist.txt", result);
console.log(result);

Live here repl.it

Upvotes: 2

Related Questions