Search code examples
javascriptarraysregexsplice

How can I add a space to an array using regex


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);

});

Solution

  • 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.