1

I have a file that outputs data in an incorrect format. I'm trying to use Javascript to correct the formatting of the file. In order for this to work all I need to do is add a space between the numbers and the A.

The problem is that I don't know what these numbers will be.

The example output from the file is as follows:

NAME 12345A JAMES
NAME 12345A JAMES
NAME 12345A JAMES
NAME 12345A JAMES

desired output:

NAME 12345 A JAMES
NAME 12345 A JAMES
NAME 12345 A JAMES
NAME 12345 A JAMES

I can't use indexOf() with a regular expression, so I've tried to first convert the data into a string, then into an array. I've been able to match each occurence of the regular expression, but when I attempt to splice in my space it won't work. it doesn't seem to like using match.index as the index. Can anyone see where I'm going wrong?

const fs = require('fs');

fs.readFile('fileName.txt', (err, data) => { 
    let regEx = /NAME \d\d\d\d\d/g;
    let convertToArray = data.toString().split("   ");
    console.log(convertToArray);

    while ((match = regEx.exec(convertToArray)) != null) {
        console.log(match.index);
    };

    let addSpace = convertToArray.splice(match.index, 0, ' ');
    console.log(addSpace);

});
5
  • 3
    Why not just data.replace(/NAME \d+(?![ \d])/g, '$& ') - regex101.com/r/XGA16H/1? Commented Feb 28, 2020 at 11:01
  • @WiktorStribiżew Why the negative look ahead? Does not seem to be useful here Commented Feb 28, 2020 at 11:05
  • @MuratKaragöz What if there is a space already? I guess a space should not be added then. We have too little information about the actual requirements, so the suggestion is quite generic. Commented Feb 28, 2020 at 11:06
  • @WiktorStribiżew That's right. Your answer is correct, so post it as one? Commented Feb 28, 2020 at 11:07
  • @WiktorStribiżew Brilliant, that's solved it thanks. Looks like I need to learn a lot more about regular expressions! Commented Feb 28, 2020 at 11:08

1 Answer 1

2

You may use .replace directly on the data:

data.replace(/NAME \d+(?![ \d])/g, '$& ')

See the regex demo.

Details

  • NAME - a substring
  • - a space
  • \d+ - 1+ digits
  • (?![ \d]) - not immediately followed with a space or another digit.

The $& in the string replacement pattern refers to the whole match value.

To handle any whitespace, replace the literal space with \s in the pattern.

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

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.