嗨,此函数添加到 javascript 中的字符串对象,您可以将其用于任何字符串。此代码的末尾向您展示了如何使用它来解决您的问题(seiied mahmood mirkhalili(majb.ms@gmail.com))
/**
* replace pattern with relative of nested pattern (a pattern in another patern)
* @param {string} input [match of regreplace]
* @param {string} input1 [match firstgroup of regreplace ]
* @param {string} input2 [match second group of regreplace ]
* @return {string} [replace string with pattern ]
*/
String.prototype.relativeInnerReplaceFunction = function (input , input1 , input2){
var firstMatch = input1.match(this.regfirst);
if(firstMatch != undefined){
firstMatch = firstMatch.length
} else {
firstMatch = 0 ;
}
var lastMatch = input1.match(this.regEnd);
if(lastMatch != undefined){
lastMatch = lastMatch.length ;
} else {
lastMatch = 0 ;
}
if(input1 != undefined && input1 != 404){
var relativeInnerReplaceFunction = this.relativeInnerReplaceFunction.bind(this);
input1 = input1.replace(this.regReplace , relativeInnerReplaceFunction) ;
}
var numLoop = firstMatch - lastMatch - 1;
if(input2 != undefined){
for (var i = 0; i < numLoop; i++) {
input2 = input2.replace(this.regReplace , this.pattern);
}
} else {
input2 = '' ;
}
return input1+input2 ;
};
/**
* replace recuresive pattern for solve problem cdata in cdata mor info in this link https://stackoverflow.com/questions/13865357/nested-cdata-correctly
* @param {regular experssion} regfirst [the start pattern ]
* @param {regular experssion} regEnd [the end pattern ]
* @param {regular experssion} regReplace [the pattern for nested replace]
* @param {string} pattern [the pattern will replace with regReplce regular pattern in nested replace]
* @return {string} [string after calculate nested pattern and replace with regreplace ]
*/
String.prototype.relativeInnerReplace = function (regfirst , regEnd, regReplace , pattern){
this.regfirst = regfirst ;
this.regEnd = regEnd ;
this.regReplace = regReplace ;
this.pattern = pattern ;
var relativeInnerReplaceFunction = this.relativeInnerReplaceFunction.bind(this);
var output = this.replace(regReplace , relativeInnerReplaceFunction) ;
return output ;
}
/*how to use
for example for nested cdata problem 'search in stackoverflow'
wpsExample.relativeInnerReplace(/<!\[CDATA\[/g , /\]\]>/g , /^(.*)(\]\]>)/g , '$1]]]]><![CDATA[>')
*/