0

Here is a fiddle http://jsfiddle.net/aLr2yx8d/

$('#inputButton').click(function() {    

    var value = $('#input').val(); 
    var re = /\./g;
    var output = $('#output');

    var text = output.text().replace(re, value);
    output.html(text); 

});

Now I can only update it once. I want to have the possibility to update it more than once. The first time it will replace the dot (.) and the second time it has to replace the first value I gave.

  • 2
    What exactly are you trying to achieve? The question is not completely clear. – Ram Oct 05 '14 at 16:15
  • You want users to be able to put text inside a placeholder (I assume), but you're taking a completely wrong approach. Provide more context. – MarioDS Oct 05 '14 at 16:15
  • [http://i.imgur.com/gqiJWC7.jpg](http://i.imgur.com/gqiJWC7.jpg) I made it visual of what I'm trying to do. – squarestripe Oct 05 '14 at 16:19

1 Answers1

1

You can use a variable to hold the variable RegularExpression you wish to change. For example:

var regExVal= /\./g;
$('#inputButton').click(function() {    

    var value = $('#input').val(); 
    var re = regExVal;
    regExVal= new RegExp(value, "g"); <-- this is how you set the new value
    var output = $('#output');

    var text = output.text().replace(re, value);
    output.html(text); 

});

Here's the JsFiddle

Edit:

As I mentioned in the comment, you would need to escape certain characters for use as characters in the Regular Expression instead of operators. I found a good answer to that in another question. Include it in your script:

function escapeRegExp(str) {
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

Then, before using the value, you do something like:

value = escapeRegExp(value);
Community
  • 1
  • 1
Guy Passy
  • 694
  • 1
  • 9
  • 32
  • 1
    Looking at the picture you put up... this won't work with the asterisk *... or ^ and $ for that matter. You would need to escape those characters from the input value before using the `replace` function – Guy Passy Oct 05 '14 at 16:26
  • I see. How would I do that exactly? – squarestripe Oct 05 '14 at 19:07
  • @squarestripe See the edited answer. It shows how to make sure that that you can use any character you want. – Guy Passy Oct 05 '14 at 22:53