使用 Javascript 获取当前 URL 的一部分

Get part of the current URL using Javascript

本文关键字:URL 一部分 Javascript 获取 使用      更新时间:2023-09-26

f我正在使用javascript传递的URL中的$_GET变量在Wordpress页面中开发一个简单而小的搜索:

<script>
function pesquisar()
{
    var pesquisar = document.getElementById('termo').value;
    var caminho = document.URL+'&pesquisa='+pesquisar;
    window.location = caminho;
}
</script>
<input type='text' id='termo'>
<input type='button' value='pesquisar' onclick='pesquisar()'>

因此,要搜索的网址是:MYURL/?page_id=51&pesquisa=test

当然,page_id是可变的。如果我再次搜索,URL将是:MYURL/?page_id=51&pesquisa=test&pesquisa=new,出了什么问题。

我如何使用javascript只获得MYURL/?page_id=51?window.location.pathname不是我需要的。

谢谢。

任何天真搜索的东西都容易受到以下问题的影响: 如果网址是:

http://example.com/?pesquisa=test&page_id=51

您需要搜索并删除相关的查询参数:

var caminho = document.URL.replace(/([?&])pesquisa=[^&]+&?/,"$1")+"&pesquisa="+pesquisar;

试试这个希望它应该有效

<script>
function pesquisar()
{
    var pesquisar = document.getElementById('termo').value;
    var caminho = location.protocol + '//' + location.host + location.pathname+'&pesquisa='+pesquisar;
    window.location = caminho;
}
</script>
<input type='text' id='termo'>
<input type='button' value='pesquisar' onclick='pesquisar()'>

试试这个。

var a = document.URL;
    var result = a.substr(0, a.indexOf('&'));

资源:

  • 在 Web 浏览器中获取当前网址

  • 如何在指定字符 jquery 或 JavaScript 之前抓取子字符串

javascript:

<script type="text/javascript">
function get_query_param(name) {
    name = name.replace(/['[]/, "'''[").replace(/[']]/, "''']");
    var regex = new RegExp("[''?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/'+/g, " "));
}
window.onload = function() {
    if (get_query_param("page_id") != null) {
        alert(window.location.pathname + "?page_id=" + get_query_param('page_id'));
    }
}
</script>

希望有帮助。