Search code examples
node.jsregexp-replace

using regex replace in node js


I'm trying to build a regex using 2 variables read from other application, the replace is in this case 'new line'. Search-part works as expected thow replaces as text '\n' instead of a new line

var replaceWith = ("'")+\n+("'");
var Search = -_-
var result = str.replace( new RegExp( Search, 'g' ), replaceWith);
    fs.writeFile(jobPath, result, 'utf8', function (err) {
      if (err) return console.log(err);
    });

await job.sendToData(Connection.Level.Success);

Original text: Publication-_-PublicationDate

*I get result: * Publication\nPublicationDate

I need: Publication PublicationDate


Solution

  • What it looks like you're looking for is the following:

    const str = 'Publication-_-PublicationDate';
    const replaceWith = ('\n');
    const Search = '-_-';
    const result = str.replace( new RegExp( Search, 'g' ), replaceWith);
    console.log(result);

    It could also be shortened to this:

    const str = 'Publication-_-PublicationDate';
    const result = str.replace('-_-', '\n');
    console.log(result);