I have a basic webapp that basically serves the same purpose as Rubular.com, but for gsub.

It runs some simple JavaScript, which POST's to a Sinatra app, which then updates page with the results.


%h1 Gsubular
%p It's like Rubular! But for y'know...Gsub!

  %h2 Gsub-ed String:
  %form#gsub_form{:method=>"POST", :action=>"/"}
    %span< .gsub!(
    %span< /
    %span /,"
    %span ")

The Sinatra POST handler:

# create
  post '/' do
    response = {}
      str = params[:test_string]
      regex_do_this = Regexp.new(params[:pattern])
      gsubbed_string = str.gsub!(regex_do_this, params[:replacement])
    rescue Exception => e
      response[:error] = e.message
      return response.to_json
    response[:gsub_string] = []

The JavaScript I reworked from someone else's JavaScript to just detect Regex looks like this:

$(function() {
  $("#gsub_pattern_input, #gsub_replacement_input, #test_string").bind('keyup', function(e){
    $.post('/', $(e.target).parents("form").serialize(), function(response){
      var results = eval("(" + response + ")");
      var result;
        result = escapeHTMLEncode(results.gsub_string[0])
        if(result == "undefined")
          result = "no matches"
        if(result == "null")
          result = "[EMPTY STRING]"
        $("#gsub_answer").css('color', 'green');
        $("#gsub_answer").css('color', 'red');

function escapeHTMLEncode(str) {
 var div = document.createElement('div');
 var text = document.createTextNode(str);
 return div.innerHTML;

// Hacky way of stopping enter from submitting...
$(document).ready(function() {
    if(event.keyCode == 13) {
      return false;

I'm not a Javascript expert, but it looks ok to me in general. I know that evals are evil, so that needs fixing.

Can anyone give me some guidance on how to clean this up a bit?

The full Github repo is here.

  • \$\begingroup\$ Could you explain what you mean by "interpolation"? \$\endgroup\$ – 200_success Feb 23 '15 at 11:00
  • \$\begingroup\$ Sorry, interpolation was a bad term, just changed to processing. \$\endgroup\$ – Peter Souter Feb 23 '15 at 11:09
  • \$\begingroup\$ You should mention that you can reference captured groups in the replace portion of the gsub \$\endgroup\$ – Devon Parsons Feb 23 '15 at 12:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.