![](/img/trans.png)
[英]How to replace text between two XML tags using jQuery or JavaScript?
[英]replace value between tags in text using javascript
我正在嘗試將以下文件中的值從“4xsddfdf”替換為“3AAAAAA”
<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>
我的代碼是
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);
但價值替換不起作用。 任何人都可以幫助解決這個問題。
語法熒光筆實際上是在突出問題:您沒有在結束標記中對欄進行轉義,因此正則表達式在那里結束。 嘗試:
var REGEX = /<ticketName>(.+)<\/ticketName>/;
演示: https://regex101.com/r/zlXfQK/1
對於評論中的附加問題,有一個代碼可以用新內容替換文件:
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');
只需將filenameOut
更改為正確的值。
之后,您有一個內容已更改的文件,您可以發送或執行任何您想做的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.