简体   繁体   English

无法解析联系表单的网址

[英]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. 我正在尝试创建一个基于URL的搜索部分(?John-Doe)填写“名称”的代码。 However, if there is no search portion, i would like it to default to the pathname. 但是,如果没有搜索部分,我希望它默认为路径名。

For instance test.com/contact?John-Doe 例如test.com/contact?John-Doe

or parse from the following if the search is not present 或从以下内容解析(如果不存在搜索)

test.com/John-Doe 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 . 在这种情况下,我将选择test.com/contact?name=John将值John设置为属性name You don't have to parse name by regex. 您不必通过正则表达式来解析名称。 Just add whitespace which can be written as %20 in URL. 只需添加可在URL中写为%20空格。

I would use URL object with searchParams function. 我将URL对象与searchParams函数一起使用。

 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 您可以在输入中显示它,而不是使用URL来使用location.href

 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" /> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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