Skip to content

Instantly share code, notes, and snippets.

@thisislawatts
Created August 29, 2013 14:42
Show Gist options
  • Save thisislawatts/6378995 to your computer and use it in GitHub Desktop.
Save thisislawatts/6378995 to your computer and use it in GitHub Desktop.
Some funny little regexes I conjured up for an edge case project.
String.prototype.replaceAllButLast = function( search, replace ) {
var tmp = this.slice(0, this.lastIndexOf(search)),
end = this.slice(this.lastIndexOf(search)),
regex = new RegExp(search.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), 'g'); // Escaping chars
return tmp.replace(regex,replace) + end;
}
String.prototype.replaceAllButFirst = function( search, replace ) {
var tmp = this.slice( this.indexOf(search)),
start = this.slice( 0, this.indexOf(search)),
regex = new RegExp(search.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), 'g'); // Escaping chars
console.log(start);
return search + tmp.replace(regex,replace);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment