1

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!

Code Maniac
  • 37,143
  • 5
  • 39
  • 60
Matt
  • 21
  • 2
  • Possible duplicate of [How can I get query string values in JavaScript?](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – ggorlen Aug 09 '19 at 19:29

2 Answers2

0

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"/>
Jax-p
  • 7,225
  • 4
  • 28
  • 58
0

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" />
Aziz.G
  • 3,599
  • 2
  • 17
  • 35
  • 1
    Thank you both for commenting, though i couldn't get either to work as i needed. I wanted to clarify something about what i am trying to achieve. my hope is that i could either have test.com/john-doe or test.com/contact?john-doe both produce John Doe in the form result. I need to have both options if possible because my company wants to be able to use 1 form for both the general contact page or the person's individual contact page so i was trying to do this by parsing the url. – Matt Aug 11 '19 at 00:42
  • i updated the code to match the name for both pages – Aziz.G Aug 11 '19 at 19:12
  • I was messing with things over the weekend and was able to work out an If/else string that accomplished what i was hoping for. I appreciate the help everyone provided! – Matt Aug 12 '19 at 20:35