代码用于映射正则表达式搜索和替换,我正在尝试从闭包中更新输入字符串。
lineNumber变量会改变但是this.data不会改变,这有点奇怪......
有人知道如何解决这个问题?
这是代码:
class regexMap {
constructor(map) {
this.map = map;
}
replace(str){
this.data = str;
for (var i = 0; i < this.map.length; i++){
var regex = new RegExp(this.map[i][0], 'ig')
this.data = this.data.replace(regex, this.map[i][1].bind(this))
}
return this.data
}
update(set){
this.data = set
return this.data
}
export(){
return this.data;
}
getLocation(args){
return args[args.length-2]
}
getLastLine(lines){
lines = this.getPreviousLines(lines)
lines = this.getLocation(lines)
return lines
}
getPreviousLines(self){
var lines = this.data.substring(0, this.data.lastIndexOf(self)).split('\n')
return lines
}
getPrevious(lines){
lines = this.getPreviousLines(lines)
lines.reverse(),lines.shift(),lines.shift(),lines.reverse()
lines = lines.join('\n')
return lines
}
getLineNumber(location){
location = this.getLocation(location)
var location = this.data.substring(0,location)
location = location.split('\n').length
return location
}
splitLines(){
var lines = this.data.split('\n');
return lines
}
removeLines(location,amount){
var lines = this.splitLines()
//console.dir(lines);
lines.splice(location, amount)
this.update(lines.join('\n'))
return lines
}
extractAll(self,args){
return {
data: this.export(),
location: this.getLocation(args),
lastLine: this.getLastLine(self),
previous: this.getPrevious(self),
previousLines: this.getPreviousLines(self),
lineNumber: this.getLineNumber(args)
}
}
}
// EXAMPLE:
// Create a regaxMap array
var map = [
[/FIND (.*)\n/g,function(self,str){
// Get all arguments and variables
var all = this.extractAll(self,arguments)
var ln = all.lineNumber
if(ln = 2){
this.update('FIND Replaced'); // <-- Doesn't work
this.removeLines(ln,1) // Will remove a line but this.data won't change
}
if(str != '' && str != undefined){
return 'find(\''+str+'\');\n'
} else {
console.error('FIND requires a string in line: '+ln+'.')
return ''
}
}],
];
console.log(new regexMap(map).replace("find something\nFIND This is, a string\nfind \n"))
感谢。