【问题标题】:jQuery Replace Strings With URLsjQuery 用 URL 替换字符串
【发布时间】:2009-09-12 04:34:05
【问题描述】:

在我的网站上,我有一些看起来像这样的字符串(可以是任何数字)

29-30-404-59556348

使用 jQuery 我想将其解析为

<a href="http://www.mysite.com/page.php?=29,30,404,59556348">Page</a>

我该怎么做?

【问题讨论】:

  • 如果我们要找到它们,您需要在页面上包含这些数字所在位置的上下文。

标签: javascript jquery regex


【解决方案1】:

这会搜索您的整个页面并替换所有数字。您可能希望指定一个比整个正文更紧密的上下文进行搜索,并且您可能希望调整正则表达式以使其匹配特定的数字模式。现在它匹配页面中的任何数字或由连字符分隔的整数序列。

// This is a simple jQuery extension to find text nodes
$.fn.textNodes = function() {
    var ret = [];
    $.each(this.contents(), function() {
        try {
        if(this.nodeType == 3) 
            ret.push(this);
        else 
            $(this).contents().each(arguments.callee);
        } catch(e) {}
    });
    return $(ret);
}

// Get all the text nodes from the body
$(document.body).textNodes().each(function() {
    // Test each text node to see if it has any numbers in it
    if(/\d/.test(this.nodeValue))
        // Remove numbers or sequences of numbers and replace with links
        $(this).replaceWith(
            this.nodeValue.replace(/\d+(?:-\d+)*/g, function(nums) {
                return '<a href="http://www.mysite.com/page.php?ids=' + nums.split('-').join(',') + '">Path</a>'; // str.split(a).join(b) is faster than str.replace(a,b)
            })
        );
});

更新:这是匹配此模式 xx-xx-xxx-xxxxxxxx 中的数字的版本

// Get all the text nodes from the body
$(document.body).textNodes().each(function() {
    // Test each text node to see if it has our pattern of numbers in it
    if(/\d{2}-\d{2}-\d{3}-\d{8}/.test(this.nodeValue))
        // Remove sequences of numbers and replace with links
        $(this).replaceWith(
            this.nodeValue.replace(/\d{2}-\d{2}-\d{3}-\d{8}/g, function(nums) {
                return '<a href="http://www.mysite.com/page.php?ids=' + nums.split('-').join(',') + '">Path</a>'; // str.split(a).join(b) is faster than str.replace(a,b)
            })
        );
});

【讨论】:

  • 太完美了 :) 但我真的很纠结正则表达式。我如何匹配这样的字符串 14-15-809-59079881 ?
  • 2 位、2 位、3 位、8 位?我会更新我的帖子。
【解决方案2】:

如果我理解正确,你可以这样做:

function getAnchor (name, code) {
  var anchor = '<a href="http://www.mysite.com/page.php?={CODE}">'+name+'</a>';
  return $(anchor.replace('{CODE}', code.replace('-',',')));
}

使用example:

$('body').append(getAnchor('Page', '29,30,404,59556348'));

【讨论】:

    【解决方案3】:
    var url = "http://www.mysite.com/page.php?ids=" + string.replace("-", ",");
    

    请注意,我已将查询字符串名称设置为 ids。您可能希望这样做以便能够在服务器端代码中更轻松地读取查询字符串值。

    【讨论】:

    • 但这不会在整个页面中搜索 ID
    • 请重新表述您的问题。我不太清楚你想做什么。
    猜你喜欢
    • 2014-03-09
    • 2013-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    相关资源
    最近更新 更多