简体   繁体   中英

replace value between tags in text using javascript

I am trying to replace value from "4xsddfdf" to "3AAAAAA" in below file

<soapenv:Envelope xmlns:soapenv="http://autocorp.com/soap/envelope">
<soapenv:Header>
    <ns2:section>something</ns2:section>
</soapenv:Header>
<soapenv:Body>
    <aut:process>
    <payload>
    <ticket:ticektpro>
        <ticketName>4xsddfdf</ticketName>
    </ticket:ticektpro>
    </payload>
</soapenv:Body>
</soapenv:Envelope>

My code is

const fs = require('fs');
const replacePath="3AAAAAA"
var REGEX = /<ticketName>(.+)</ticketName>/;
console.log(REGEX)
var fileContent = fs.readFileSync('query_request.txt', 'utf8');
matchresult = fileContent.match('<ticketName>4xsddfdf</ticketName>');
console.log('------------------------------match',matchresult)
fileContent = fileContent.replace(REGEX, function replacer(matchresult,replacePath) {
  // load and return the replacement file
console.log('----------------------------------',fileContent)
  return fs.readFileSync(replacePath, 'utf8');
});
console.log(fileContent)
fs.writeFileSync('query_request.txt', fileContent);

but the value replacement is not working. can any one help on this.

The syntax highlighter is actually highlighting the problem: you are not scaping the bar in the closing tag so the regex ends there. Try with:

var REGEX = /<ticketName>(.+)<\/ticketName>/;

Demo: https://regex101.com/r/zlXfQK/1

For the additional question in comments, there's a code that replaces the file with the new contents:

const fs = require('fs');
const replacePath="3AAAAAA";
const filenameIn = 'query_request.txt';
const filenameOut = 'query_request_out.txt';
var REGEX = /<ticketName>(.+)<\/ticketName>/;
var fileContent = fs.readFileSync(filenameIn, 'utf8');
fileContent = fileContent.replace(
    REGEX,
    '<ticketName>' + replacePath + '</ticketName>'
);
fs.writeFileSync(filenameOut, fileContent, 'utf8');

Just change filenameOut to the correct value.

After that you have a file with the contents changed that you can send or whatever you want to do.

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