javascript(node.js)将url哈希转换为带有参数的url

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

  • 将原始域replace为另一个域。
  • 将url的散列值转换为带有参数的url(仅限特定域名(website.com))。

这是我最初的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

提前致谢

Node.js有一个用于parsing和构造URL的内置模块。 您的解决scheme可以写成:

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

假设所有的链接遵循相同的模式,你的JSON对象看起来像这样

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

你可以使用一个简单的正则expression式来提取ID并像这样构build你的新链接

 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来尝试一下。