Search code examples
node.jsregexescapingregexp-replace

Nodejs adding extra backslash(\) in string


I am trying this sample code

let route = {
                paths: []
            }
            
let convertedStr0 = "/{test}/search/v1/{userId}"

let convertedStr1 = convertedStr0.replace(new RegExp("{", 'g'), "(?<").replace(new RegExp("}", 'g'), ">\\S+)$");

console.log(convertedStr1);  //Output: /(?<test>\S+)$/search/v1/(?<userId>\S+)$

route.paths[0] = convertedStr1;
console.log(route); //Output: { paths: [ '/(?<test>\\S+)$/search/v1/(?<userId>\\S+)$' ] }

I need to write the route result in a file with single backslash (\). But an extra backslash is appended. Any one has any suggestion how I can fix this issue?


Solution

  • If you want to keep the single backslash in the output file, first stringify your route object and then replace the double slash with a single one:

    route = JSON.stringify(route, null, 2)
                .replaceAll("\\\\","\\");
    console.log(route); //Output: { "paths": [ "/(?<test>\S+)$/search/v1/(?<userId>\S+)$" ] }