我有一个脚本搜索网址并查找某个域名,然后将一些参数附加到网址的末尾。但是,如果运行多次,它会将重复的参数添加到同一个URL。是否有可能检查网址上是否已有参数?
正在修改的代码
<div id="wp-content-editor-container" class="wp-editor-container"><textarea class="wp-editor-area" rows="10" tabindex="1" cols="40" name="content" id="content"><a title="Link to test domain" href="http://www.domain.com">Link to google</a>
<a href="http://google.com/directory/subdirectory/index.html">This is another link</a>
<a href="http://domain.com/directory/index.html">This is a 3rd link</a>
<a href="http://www.domain.com/subdir?parameter">this url already has parameters</a></textarea></div>
jquery脚本
var url = 'www.domain.com';
var append = '?parameter';
$(".wp-editor-area").each(function() {
$(this).text(urlify($(this).text()));
});
function urlify(text) {
var urlRegex = /(\b(https?|ftp|file):\/\/[www.domain.com][-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(urlRegex, function(url) {
return url + append;
})
}
当前输出
<a title="Link to test domain" href="http://www.domain.com?parameter">Link to google</a>
<a href="http://google.com/directory/subdirectory/index.html">This is another link</a>
<a href="http://domain.com/directory/index.html?parameter">This is a 3rd link</a>
<a href="http://www.domain.com/subdir?parameter?parameter">this url already has parameters</a>
理想的输出不会在url ^
的末尾添加第二个“?参数”谢谢!
答案 0 :(得分:2)
我认为您可以使用indexOf检查网址是否已包含您要追加的内容。
function urlify(text) {
var urlRegex = '/(\b(https?|ftp|file):\/\/[www.domain.com][-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig';
return text.replace(urlRegex, function (url) {
// if the url does not contain append, concat append to the URL
if (url.indexOf(append) == -1) {
return url + append;
}
return url;
});