繁体   English   中英

将URL的一部分重写为链接

[英]Rewriting one part of a URL into a link

我正在尝试将URL的一部分插入另一部分。

地址栏中的URL将显示为domain.com/test.php?/12345,然后页面中的链接必须变为domain.com/do/Login/12345(此结束号对于每个用户都会更改)

(请注意,我无法更改URL domain.com/test.php?/12345,因为网站所有者已经设置了该URL。)

对于上述网址,我必须删除http:// www 部分,因为新用户不能提交多个链接来防止垃圾邮件。 最终脚本应包含http:// www

您将能够看到,我所需要的只是末尾的数字,即12345,但我不太确定如何实现此目的(javascript初学者)。 这是我到目前为止的内容:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Path test</title>
</head>

<body>

<script>
// get URL eg http://www.domain.com/test.php?/12345
newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
</script>

<script>
//write new domain then add user number ie 12345
document.write('http://www.domain.com/do/Login/' + window.location.pathname);
</script>
</body>
</html>

这显然行不通,但显示了我的去向。

使用http://www.sitepoint.com/forums/showthread.php?t=244955上找到的脚本,我有些运气,但它只能用于扩展名为.html,.php等的文件名。

有任何想法吗?

提前致谢。

首先,您需要获取问号后面的部分网址。 这在

 window.location.search

变量。 请注意,该名称已经包含“ /”。 然后,您需要创建实际的链接。 document.write('http:// ...)将不起作用,因为这只会以文本形式编写它,而不会成为实际的定位标记。 为此,您需要类似:

document.getElementById("yourLink").href = "http://domain.com/do/Login" + window.location.search

不要忘记在html中放置一个锚标签,其ID与上面的getElementById()方法中的元素相匹配。 如果您不想在HTML标记中添加锚标记,则可以使用javascript创建一个标记,例如:

var link = document.createElement('a');
link.href = "http://domain.com/do/Login" + window.location.search;
document.body.appendChild(link);

这可能需要进一步调整以适应您的需求。

这样行吗? 它使用整个URL,将其与“?”分开 (意味着从参数开头开始),然后将参数连接到基本URL。

var oldUrl = window.location.href;
var parameters = oldUrl.substring(oldUrl.indexOf('?',0),oldUrl.length);

var newUrlBase = 'http://www.domain.com/do/Login/';
var newUrl = newUrlBase + parameters;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM