regex / jquery在div中查找域名(url)并附加参数

时间:2012-07-19 22:05:55

标签: javascript jquery regex

Previous stackoverflow

此jquery语句将查找domain.com并将附加?参数添加到URL的末尾。如果已添加?参数,则不会附加。

问题:我当前的jquery修改了所有URL而不是domain.com。这是我想要使用的正则表达式语句,并且经过测试可以正常工作。但是,实现时,不会附加任何内容。非常感谢任何帮助!

我想使用正则表达式:

\b(https?://)?([a-z0-9-]+\.)*domain\.com(/[^\s]*)?

RegexFiddle

JSFiddle为了方便

要修改的代码

<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://www.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) {
        // if the url does not contain append, concat append to the URL
        if (url.indexOf(append) == -1) {
            return url + append;
        }
        return url;
    });

}

当前输出

    <a title="Link to test domain" href="http://www.domain.com?parameter">Link to google</a>
<a href="http://www.google.com/directory/subdirectory/index.html?parameter">This is another link</a>
<a href="http://domain.com/directory/index.html?parameter">This is a 3rd link</a>

1 个答案:

答案 0 :(得分:2)

测试此代码 - 它应该是您需要的(或至少起点)&gt;&gt;

function urlify(text) {
  var append = '?parameter';
  text = text.replace(/("(?:(?:https?|ftp|file):\/\/)?(?:www.|)domain.com(?:\/[-a-z\d_.]+)*)(\?[^"]*|)(")/ig,
    function(m, m1, m2, m3) {
      return ((m1.length != 0) && (m2.length == 0)) ? m1 + append + m3 : m;
    });
  return text;
}

$(".wp-editor-area").each(function() {
  this.innerHTML = urlify(this.innerHTML);
});