1

我有一个脚本,它通过 url 搜索并查找某个域名,然后将一些参数附加到 url 的末尾。但是,如果多次运行,它会将重复的参数添加到同一个 url。是否可以检查 url 是否已经有参数?

JSFiddle

原始的stackoverflow帖子

正在修改的代码

<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">&lt;a title="Link to test domain" href="http://www.domain.com"&gt;Link to google&lt;/a&gt;
&lt;a href="http://google.com/directory/subdirectory/index.html"&gt;This is another link&lt;/a&gt;
&lt;a href="http://domain.com/directory/index.html"&gt;This is a 3rd link&lt;/a&gt;

&lt;a href="http://www.domain.com/subdir?parameter"&gt;this url already has parameters&lt;/a&gt;</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 的末尾添加第二个“?参数”^

谢谢!

4

1 回答 1

2

我认为您可以使用 indexOf 来检查 URL 是否已经包含您要附加​​的内容。

  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;
                });
于 2012-07-11T20:41:39.287 回答