如何在Vite的Javascript与HTML中实现空格转短横线功能?
Alright, let's get to the bottom of why your space-to-dash conversion is resulting in %20 instead of hyphens, and fix it for your Weebly site.
The Root Cause
Looking at your existing code, the biggest issue is that your form has a name="type" attribute. type is a built-in property of the document object, so document.type.input isn't reliably pointing to your input field. That means your replace(/\s/g, "-") logic is probably not even executing—so spaces are still being URL-encoded as %20 when you redirect.
Other minor issues include duplicate onclick events on your submit button and inconsistent case handling between your onkeyup and CheckPassword function.
Modified Code
Let's fix these step by step:
Updated HTML
<form method="post" action="ingen_javascript.htm" onsubmit="CheckPassword();return false;" name="siteForm"> <pre> <input type="text" placeholder="Type in a website" name="input" list="autocomplete" onkeyup="document.getElementById('identifier').value=this.value.replace(/\s/g,'-').toLowerCase();" autofocus> </pre> <input type="submit" value="Vite" style="height: 0px; width: 0px; border: none; padding: 0px;" hidefocus="true"> </form>
Updated JavaScript
function CheckPassword() { // Grab the input value correctly using the renamed form var input = document.forms['siteForm']['input'].value; // Replace all spaces (including consecutive ones) with single hyphens, and lowercase the input input = input.replace(/\s+/g, "-").toLowerCase(); // Clean up any consecutive hyphens that might result from multiple spaces input = input.replace(/-+/g, "-"); // Redirect to the processed URL location.href = input + '/'; }
Key Changes Explained
- Renamed the form: Changed
name="type"toname="siteForm"to avoid conflicts with the browser's built-indocument.typeproperty. Now we can reliably access the input field withdocument.forms['siteForm']['input'].value. - Improved regex handling:
/\s+/gmatches one or more spaces, converting them directly to a single hyphen (no more multiple hyphens from consecutive spaces)./-+/gcleans up any accidental consecutive hyphens to keep your URLs clean.
- Consistent case conversion: Added
.toLowerCase()to match theonkeyupbehavior, ensuring your redirect URLs are consistently lowercase. - Removed duplicate events: Stripped the extra
onclickfrom the submit button—your form'sonsubmitalready triggers the function, so duplicate events were unnecessary and could cause conflicts.
Testing
After updating the code, test with input like Google Search—it should redirect to yoursite.com/google-search/ (no %20 in sight). If you still run into issues, double-check that your JS file is properly linked in your Weebly theme and that there are no other scripts interfering with form handling.
内容的提问来源于stack exchange,提问作者MULTI Team

