in the following Snippet (Example) you can see that I tried to build a function for more comfortable string-replacements in my project.
Really soon I found out that it's necessary to connect the regex-syntax with a variable, and found this regEx-Objekt solution in this topic.
But after hours of try(outs), I realized that my this solution didn't really worked, because it converts the slashes to a string, and at the end we have a simple string again.
The following example focused a URL to replace. I like this example, because we have the Slashes in out pattern and 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\/';
// With Function
$('#a').html('[RESULT 1] ' + replaceThis(example_input, example_pattern, example_target));
// With 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 for a string like:
'/http://localhost//g'
Not liked assumed/wished:
/http://localhost//g
Which should lookup for a string like:
'http://localhost/'
Any ideas how to handle/solve this? I'm working since hours on that.