2014-03-01 21 views
2

到網址我有一個大的靜態結果和我想以下變化:的JavaScript(Node.js的)轉換網址哈希與參數

  • 替換原始域到另一個。
  • 使用僅針對特定域名(website.com)的帖子ID將參數的網址哈希值轉換爲具有參數的網址。

這與3個環節和2型動物的域名我原來的靜態結果,例如:

var json = {This is the static result with many links like this <a href=\"http://website.com/932427/post/something-else/\" target=\"_blank\"> and this is other link obviusly with another post id <a href=\"http://website.com/456543/post/another-something-else/\" target=\"_blank\">, this is another reference from another domain <a href=\"http://onother-website.com/23423/post/please-ingnore-this-domain/\" target=\"_blank\"> } 

因此,原件的URL我需要改變兩個,與上面的例子根據:

http://website.com/932427/post/something-else/ 
http://website.com/456542/post/another-something-else/ 

而且我想改變這種格式現在鏈接:

http://other_domain.com/id?=932427/ 
http://other_domain.com/id?=456543/ 

最終結果應該看起來像這樣進入靜態結果。

通過我提前瞭解如何使用Node.js

感謝的方式

+0

您是否嘗試做某件事? –

+0

你的意思是重定向嗎?你使用HTTP的任何框架? – Bergi

+0

'json'看起來不像真正的JSON。看看正則表達式(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)。然後,您將能夠找到所需的鏈接,並以您需要的某種方式替換/重新格式化它們。 –

回答

3

Node.js有一個用於解析和構造URL的內置模塊。您的解決方案可寫爲:

var url = require('url'); // Comes with Node. 

// Get the path: '/932427/post/something-else/' 
var path = url.parse('http://website.com/932427/post/something-else/').path; 

var newUrl = url.format({ 
    protocol: 'http', 
    host: 'other_domain.com', 
    query: { id: path.split('/')[1] } 
}); 
0

假設所有環節遵循相同的模式,你的JSON對象看起來像這樣

var json = { 
    urls: [ 
     'http://website.com/932427/post/something-else/', 
     'http://website.com/456542/post/another-something-else/'  
    ] 
}; 

你可以使用簡單的正則表達式來提取ID並構建你的新鏈接像這樣

var idPattern = /\/(\d{6})\//; // matches 6 digits inside slashes 
var newUrlFormat = 'http://other_domain.com/id?={id}/'; 
var newUrls = []; 

json.urls.forEach(function (url) { 
    var id = idPattern.exec(url)[1]; 
    newUrls.push(newUrlFormat.replace('{id}', id)) 
}); 

看到這個jsfiddle來嘗試一下。

+0

Thaks,我會試試看! – user3368141

+0

這會起作用,但肯定不是一個可靠的解決方案。更好地使用Node.js內置插件,請參閱其他答案。 – djechlin

+0

我不認爲我的解決方案不夠健壯,但我同意使用內置的NodeJS模塊是更好的方法。它也使更多的可讀代碼。我提出了另一個答案。 – flitig