Skip to content

Instantly share code, notes, and snippets.

@d4n5h
Last active October 4, 2016 17:35
Show Gist options
  • Save d4n5h/efb5882ea7f1f677e2a15100eb125f46 to your computer and use it in GitHub Desktop.
Save d4n5h/efb5882ea7f1f677e2a15100eb125f46 to your computer and use it in GitHub Desktop.
regexMap - Mapped Search & Replace (JavaScript)
// EXAMPLE:
// Create a regaxMap array
var map = [
[/FIND (.*)/g,function(self,str){
// Get all arguments and variables
var all = this.extractAll(arguments,self)
// Get current line location/number
var ln = all.lineNumber
if(str != '' && str != undefined){
return 'find(\''+str+'\');'
} 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"))
class regexMap {
constructor(map) {
this.map = map;
this.data;
}
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
}
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 ln = this.data.substring(0,location)
ln = ln.split('\n').length
return ln
}
extractAll(args,self){
var array = {
data: this.data,
location: this.getLocation(args),
lastLine: this.getLastLine(self),
previous: this.getPrevious(self),
previousLines: this.getPreviousLines(self),
lineNumber: this.getLineNumber(self)
}
return array
}
update(set){
this.data = set
return this.data
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment