如何用单个函数移除字符串中从'data'到末尾的内容?
Solution to Remove Substring From 'data' to End of URL
Hey there! I see you're trying to strip off everything from the substring 'data' to the end of your URL strings, regardless of what variable content comes after 'data'—great question, let's get this sorted.
The Core Idea
We just need to find where the 'data' substring starts in the URL, then grab everything before that point. This works no matter what unpredictable content follows 'data' in your URLs.
Function Implementation
Here's a simple, robust JavaScript function that does exactly what you need:
function trimAfterData(url) { // Locate the starting index of the 'data' substring const dataStartIndex = url.indexOf('data'); // If 'data' exists in the string, return the part before it; else return original URL return dataStartIndex !== -1 ? url.slice(0, dataStartIndex) : url; }
Test It With Your Examples
Let's plug in your sample URLs to verify the result:
const firsturl = "www.google.com/sample/data/merge.html"; const secondurl = "www.google.com/sample/data/change.html"; console.log(trimAfterData(firsturl)); // Output: "www.google.com/sample/" console.log(trimAfterData(secondurl)); // Output: "www.google.com/sample/"
Using It With window.location.href
If you're working with the current page's URL, you can integrate the function like this:
let currentUrl = window.location.href; const cleanedUrl = trimAfterData(currentUrl); // Use the cleaned URL however you need console.log(cleanedUrl);
Why This Works
url.indexOf('data')finds the first occurrence of 'data' in the string and returns its starting position. If 'data' isn't present, it returns-1.url.slice(0, dataStartIndex)extracts the portion of the string from the beginning up to (but not including) the start of 'data', which gives you exactly the truncated URL you want.- The ternary operator handles the edge case where 'data' isn't in the URL, so we just return the original string instead of breaking things.
内容的提问来源于stack exchange,提问作者Beginner
相关产品推荐
相关产品推荐

