javascript(node.js)使用参数将url hash转换为url

时间:2014-03-01 16:29:35

标签: javascript node.js express

我有一个很大的静态结果,我正在尝试以下更改:

  • 将原始域名替换为另一个域名。
  • 仅使用特定域(website.com)的帖子ID将url的哈希值转换为带参数的url。

这是我原来的静态结果示例,包含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\"> }

因此,根据上面的例子,我需要改变的原始网址是两个:

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

提前致谢

2 个答案:

答案 0 :(得分:4)

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] }
});

答案 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进行试用。