简体   繁体   中英

How to find a chunk and replace in a long string using javascript

I have a long string and I want to replace server:${address.ip()}:3000 with server:localhost:3000

Here is a string

function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.environment={production:!0,server:"localhost:3000",apikey:"XXXX"}},BRrH:function(t,e,n){t.exports=c;var r=n("bkOT")("simple-peer"),o=n("3oOE"),i=n("P7XM")

What I am doing is

update-ip.js

import replace from "replace-in-file";
import * as address from "address";

export class UpdateIpService {

    constructor() {

    }

    static update(filepath: string) {
        replace({
            files: filepath,
            from: /server:\s*[`'"]http?:\/\/.*?[`'"],/g,
            to: `server: 'http://${address.ip()}:3000/',`
        }).then(changes => {
            console.log(`Ip address updated in file: ${changes}`)
        }).catch(err => {
            console.log('File could not be found to modify')
        })
    }

}

UpdateIpService.update('./main.js')

How to modify, please guide!!!

Your regex matches http where the p is optional because of the question mark. Also if you use the trailing , in and you replace the full match then that comma will also be replaced.

Without matching the http part, you could match server: and then match from the starting delimiter until the closing delimiter.

As mentioned in the comments, you could use a backreference to the first capturing group so that for example server:"localhost:3000' does not match.

\bserver:\s*([`'"]).*?\1

Explanation

  • \\bserver\\s* Match server followed by 0+ whitespace characters and use a word boundary \\b to make sure server is not part of a longer word
  • ([`'"]) Capture one of the matched characters from the character class in the first capturing group
  • .*? Match 0+ times any character non greedy
  • \\1 Match backreference to captured group 1

See the regex demo

For example:

from: /\bserver:\s*([`'"]).*?\1/g,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM