【发布时间】:2015-06-15 10:32:39
【问题描述】:
在以下片段(示例)中,您可以看到我尝试构建一个函数,以便在我的项目中更舒适地替换字符串。
很快我就发现有必要将正则表达式语法与变量连接起来,并在topic 中找到了这个 regEx-Objekt 解决方案。
但经过数小时的尝试(尝试),我意识到我的这个解决方案并没有真正奏效,因为它将斜杠转换为字符串,最后我们又得到了一个简单的字符串。
以下示例重点关注要替换的 URL。我喜欢这个例子,因为我们有 Slashes in out 模式和输入:
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>
你可以看到:
var regex = new RegExp('/' + valPattern + '/', "g");
应该查找如下字符串:
'/http://localhost//g'
假设/希望不喜欢:
/http://localhost//g
应该查找如下字符串:
'http://localhost/'
任何想法如何处理/解决这个问题? 我从几个小时就开始工作了。
【问题讨论】:
标签: javascript regex variables slash