jQuery用于识别URL和附加参数

jQuery to identify URL and append parameters

本文关键字:参数 URL 用于 识别 jQuery      更新时间:2023-09-26

这个jQuery代码将在wordpress编辑器中作为书签运行。书签/jQuery 代码将编辑内容字段中的文本并附加一个参数(例如?参数(到网址的末尾。

URL 始终是相同的域名(例如 domain.com(。但是,URL 通常包含目录(例如 domain.com/directory/index.html?parameter(。我需要附加jQuery代码,无论域名后面是什么。

最复杂的情况是domain.com/directory/index.html?someotherparameter?parameter.此内容区域通常包含多个 URL,因此脚本需要遍历整个文本。

我的半工作代码

var url= 'domain.com';
var append = ' ?parameter ';
$(".wp-editor-area").each(
    function(){
        var haystack = $(this).text();
        $(this).text(haystack.replace(url, url+ append));
    });

它正在修改的 HTML 代码

<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="This is a hyperlink" href="http://domain.com/directory"&gt;This is a hyperlink&lt;/a&gt;</textarea></div>

其电流输出

<a title="This is a hyperlink" href="http://domain.com ?parameter /directory">This is a hyperlink</a>

为了方便起见,Jsfiddle

请注意,我的输出不会在整个 URL 之后追加。如果文档正文中有更多 URls,我如何修改更复杂的 URL 并循环遍历文档?

我能找到的唯一相关和类似的问题是这个,但我无法复制结果。

谢谢!!

首先,小提琴。

您的

示例代码完全按照您的要求执行。它将字符串的'domain.com'部分替换为域和参数。一旦它找到'domain.com'它就停止寻找是否有其他附着物。

尝试使用正则表达式查找字符串中的 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">
        &lt;a title="This is a hyperlink" href="http://domain.com/directory"&gt;This is a hyperlink&lt;/a&gt;
        &lt;a title="This is another hyperlink" href="http://google.com/directory"&gt;This is another hyperlink&lt;/a&gt;        
    </textarea>
</div>​

Javascript:

var url = 'domain.com';
var append = '?parameter ';
$(".wp-editor-area").each(function() {
    $(this).text(urlify($(this).text()));
});
function urlify(text) {
    var urlRegex = /('b(https?|ftp|file):'/'/[domain.com][-A-Z0-9+&@#'/%?=~_|!:,.;]*[-A-Z0-9+&@#'/%=~_|])/ig;
    return text.replace(urlRegex, function(url) {
        return url + append;
    })
}​