[英]javascript (node.js) convert url hash to url with parameters
我有一个很大的静态结果,我正在尝试以下更改:
这是我原来的静态结果示例,包含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
提前致谢
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] }
});
假设所有链接都遵循相同的模式,并且您的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尝试一下。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.