WasiF
WasiF

Reputation: 28847

How to match from start and end and, replace string in javascript

I want to change a string/line of a file main.js from another file replace.js

I want to change the server property dynamically based on machine ip

main.js

export const environment = {
  production: false,
  server: `http://localhost:3000`,
  apikey: `X199`
};

replace.js

const replace = require('replace-in-file')
const address = require('address')

replace({
    files: 'main.js',
    from: /^server:\..*3000,$/g,
    to: `http://${address.ip()}:3000`
})

I have tested multiple regex but none was working for me.

Upvotes: 1

Views: 78

Answers (1)

Ray Chan
Ray Chan

Reputation: 1180

Try using

replace({
    files: 'main.js',
    from: /server:\s*[`'"]https?:\/\/.*?[`'"],/g,
    to: `server: 'http://${address.ip()}:3000',`
})

The anchor tags ^$ is not needed because the string 'server: http://localhost:3000' is not started at the very beginning of the file, and is not ended at the very end of the file.

Upvotes: 1

Related Questions