2009-09-12 59 views
1

我的網站上我有一個看起來像這樣(可以是任何數字)弦數的jQuery替換字符串使用URL

29-30-404-59556348 

使用jQuery我想解析成

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

這怎麼我會這樣做嗎?

+0

您需要包括在哪裏這些數字將居住在網頁上的背景,如果我們要找到它們。 – Garrett 2009-09-12 04:42:34

回答

3

它會搜索你的整個頁面,並取代所有數字。你可能想要指定一個更緊密的上下文來搜索,而不是整個正文,你可能想要調整正則表達式,使它匹配特定的數字模式。現在它匹配頁面中的任何數字或用連字符分隔的整數序列。

// 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) 
      }) 
     ); 
}); 
+0

這是完美的:)但我真的很糾結與正則表達式。我如何匹配這樣的字符串14-15-809-59079881? – 2009-09-12 07:07:42

+0

2位數,2位數,3位數,8位數?我會更新我的帖子。 – Prestaul 2009-09-12 07:37:13

0
var url = "http://www.mysite.com/page.php?ids=" + string.replace("-", ","); 

請注意,我已將querystring名稱設置爲ID。您可能想要這樣做,以便能夠在服務器端代碼中更輕鬆地從查詢字符串值中讀取數據。

+0

但是,這並不搜索整個頁面的ID – 2009-09-12 04:39:48

+2

請重新說明你的問題。我不清楚你想要做什麼。 – 2009-09-12 04:41:47

1

如果我理解正確的話,你可以做這樣的事情:

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'));