如何用jQuery获取当前URL、提取斜杠间指定字符串及修复跳转问题
Hey there! Let's break down your three tech needs and fix that search autocomplete issue together.
Fun fact: jQuery doesn't have a dedicated method for grabbing the current URL—we can just use native JavaScript's window.location.href directly. If you want to wrap it in a jQuery-style function for consistency, you could, but it's totally unnecessary. Here's how to do it simply:
// Grab the full current URL const currentUrl = window.location.href; console.log(currentUrl); // Outputs something like "https://www.example.com/foo/bar/id/1"
If you only need the path part (like /foo/bar/id/1), use window.location.pathname instead.
Let's say you want to pull "foo" from www.example.com/foo/bar/id/1. The key is to split the URL's path into segments and grab the one you need. Here's a step-by-step approach:
// First, get the path part of the URL const path = window.location.pathname; // Split the path by slashes, then filter out empty strings (from leading/trailing slashes) const pathSegments = path.split('/').filter(segment => segment !== ''); // Grab the first segment ("foo" in your example) const targetSegment = pathSegments[0]; console.log(targetSegment); // Outputs "foo"
If you need to extract something like the ID after /id/ (like "1" in the example), use a regular expression instead:
const idMatch = path.match(/\/id\/(\d+)/); if (idMatch) { const id = idMatch[1]; console.log(id); // Outputs "1" }
Looking at your code, the problem is super clear—you used an assignment operator (=) instead of a comparison operator (===) in your if statement, plus the logic itself was off. Let's fix that:
Your Original Problem Code:
select: function(event, ui) { if(window.location.href = "news/" + ui.item.slug){ window.location.href =null; } else window.location.href ="news/" + ui.item.slug; }
The = in the if condition was immediately setting window.location.href to your target path, which caused unexpected jumps. Also, comparing the full URL to a relative path would never match, and setting window.location.href = null isn't valid for navigation.
Fixed Code:
select: function(event, ui) { // Prevent default autocomplete behavior (like filling the input) if you don't want it event.preventDefault(); // Build your target relative path const targetPath = "news/" + ui.item.slug; // Get the current path without the leading slash to match the target format const currentPath = window.location.pathname.replace(/^\//, ''); // Only jump if we're not already on the target page if (currentPath !== targetPath) { window.location.href = targetPath; } }
This checks if we're already on the page we want to jump to—if yes, do nothing; if not, navigate to it. No more weird jump behavior!
内容的提问来源于stack exchange,提问作者Ali Özen

