从 href 中删除字符串

Remove string from href

本文关键字:字符串 删除 href      更新时间:2023-09-26

我在下面有这段代码,它指的是href,通常只是像"#programs"这样的同页链接。但是,我现在需要一些链接来引用其他页面,例如"/index.html#programs"。所以我的问题是,我如何将下面代码中的"href"编辑为数字符号及其后的所有内容?谢谢。

    var lastId, topMenu = $("#main-menu"),
topMenuHeight = topMenu.outerHeight() + 500;
menuItems = topMenu.find('a');
    scrollItems = menuItems.map(function () {
        content = $(this).attr("href");
        if(content){
            var checkURL = content.match(/^#([^'/]+)$/i);
            if(checkURL){
                var item = $($(this).attr("href"));
                if (item.length) return item
            }
        }
    });

你可以像这样给出新的路径:

var path = "ur_new_location";
$("#link1").attr('href',path);
var item = "/index.html#programs";
var afterHash = item.substr(item.indexOf("#"))

这里的诀窍是 indexOf 和 substr 方法

var lastId, topMenu = $("#main-menu"),
topMenuHeight = topMenu.outerHeight() + 500;
menuItems = topMenu.find('a');
    scrollItems = menuItems.map(function () {
        content = $(this).attr("href");
        if(content){
            var checkURL = content.match(/^#([^'/]+)$/i);
            if(checkURL){
                var item = $($(this).attr("href"));
                item = item.substr(item.indexOf("#"))
                if (item.length) return item
            }
        }
    });

如果是我,我会忘记替换所有文件名并使用锚标签的hash property来获得您想要的

将您拥有的过滤器替换为:

.filter(function(){
  return this.hash==='#' +id;
});

简单演示