-1

以前的堆栈溢出

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

问题:我当前的 jquery 修改了所有 URL 而不是 domain.com。这是我想使用并经过测试可以工作的正则表达式语句。但是,在实施时,没有附加任何内容。任何帮助是极大的赞赏!

我想使用的正则表达式:

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

正则表达式小提琴

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>
4

1 回答 1

2

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

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);
});
于 2012-07-20T12:24:42.677 回答