javascript - Variable in RegEx - Turns RegEx Syntax to String - How to avoid? -
in following snippet (example) can see tried build function more comfortable string-replacements in project.
really found out it's necessary connect regex-syntax variable, , found regex-objekt solution in topic.
but after hours of try(outs), realized solution didn't worked, because converts slashes string, , @ end have simple string again.
the following example focused url replace. example, because have slashes in out pattern , input:
function replacethis(valinput, valpattern, valreplace) { var regex = new regexp('/' + valpattern + '/', "g"); return valinput.replace(regex, valreplace); } example_input = 'http://localhost/images/important.jpg'; example_target = '/applications/ampps/www/'; example_pattern = 'http:\/\/localhost\/'; // function $('#a').html('[result 1] ' + replacethis(example_input, example_pattern, example_target)); // strings (without function) $('#b').html('[result 2] ' + 'http://localhost/images/important.jpg'.replace(/http:\/\/localhost\//g, '/applications/ampps/www/'));
p { font-family: verdana; margin: 2p 5px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p id="a">a</p> <p id="b">b</p>
you can see:
var regex = new regexp('/' + valpattern + '/', "g");
which should lookup string like:
'/http://localhost//g'
not liked assumed/wished:
/http://localhost//g
which should lookup string like:
'http://localhost/'
any ideas how handle/solve this? i'm working since hours on that.
when use regexp object notation, pass first argument pattern without /
, second argument flags.
and double escape it.
so /\w{0,9}/g
new regexp('\\w{0,9}','g');
so function be:
function replacethis(valinput, valpattern, valreplace) { var regex = new regexp(valpattern , "g"); return valinput.replace(regex, valreplace); }