简体   繁体   中英

Trouble parsing a url for contact form

I am trying to create a code that will fill in "name" based on the search portion (?John-Doe) of a url. However, if there is no search portion, i would like it to default to the pathname.

For instance test.com/contact?John-Doe

or parse from the following if the search is not present

test.com/John-Doe

<script type="text/javascript">

window.onload=function() {
   document.getElementById('name').value = window.location.pathname.substr(1).replace(/-/g, " ");
}

</script>

thanks for any help you can provide!

You should consider attribute layout. They are usualy in pair with name and value. In this situation i would choose test.com/contact?name=John which set value John to attribute name . You don't have to parse name by regex. Just add whitespace which can be written as %20 in URL.

I would use URL object with searchParams function.

 var target_url = "http://www.text.com/contact?name=John%20Doe"; // or window.location.href var url = new URL(target_url); var name = url.searchParams.get("name"); var input = document.getElementById("name"); if (input && name !== 'null') input.value = name; 
 <input id="name"/> 

Instead of url use location.href then you can show it in your input

 const url = "test.com/contact?John-Doe" const [name] = url.match(/\\/(.)*/); const find = name.indexOf("contact?"); const formattedName = name.substring(find > -1 ? 9 : 1, name.length).replace(/-/g, " "); document.getElementById("name").value = formattedName; 
 <input id="name" /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM