Action Directory / Pattern Find & Replace

Install

Replaces all instances of a regular expression in the current selection or entire document

Shared by @eichtyler

Script

// JavaScript strings are escaped, but we want to use the characters without escaping.
// e.g. converts "\t" to a tab character
function unSlash( input ) {
	var chars = {
		"\\\\'": "\'",
		"\\\\\"": "\"",
		"\\\\\\\\": "\\",
		"\\\\n": "\n",
		"\\\\r": "\r",
		"\\\\t": "\t",
		"\\\\b": "\b",
		"\\\\f": "\f"
	};

	for ( var raw in chars ) {
		var char = chars[raw];
        var pattern = new RegExp( raw, "g" );
		input = input.replace( pattern, char );
	}

	return input;
}

ui.input( 'Find pattern…', '', 'Regular Expression', function( pattern ) {
	if ( !pattern ) return;
	
	ui.input( 'Replace "' + pattern + '" with…', function( replacement ) {
		if ( replacement === undefined ) return;

		var text = editor.getSelectedText();
		var method = 'replaceSelection';
		if ( !text ) {
			text = editor.getText();
			method = 'setText';
		}

		var regex = new RegExp( pattern, 'gm' );

		text = text.replace( regex, unSlash( replacement ) );
		editor[ method ]( text );
	});
});