1

On my site I have a HTML form like the following:

<label>Name</lable>
<input name="username" id="username19" type="text" value="">

and let's say that the link in the address bar of the browser is:

https://sitename.com/consulting/order-plan/#ref/testing**

I want to do following thing:

Pick the URL from the browser address bar and split it by "/". After choose the last word in this case it's "testing" and insert it to the form value with the ID "username19"

Could you help me to do this with Javascript or jQuery?

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Sergi Khizanishvili
  • 537
  • 1
  • 7
  • 16
  • 1
    Have a look here - http://stackoverflow.com/questions/39619951/regular-expression-for-link/39620022#39620022 – Millard Apr 11 '17 at 10:43
  • Are you going to bind it to an event, like click or sth? Or right after the document load? – Rüzgar Apr 11 '17 at 11:06

4 Answers4

1

You could get the current path from the address bar using window.location.pathname then split it using substr and finally get the last part using lastIndexOf('/') like :

var current_path_name = window.location.pathname
console.log( current_path_name.substr(current_path_name.lastIndexOf('/') + 1) );

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
1

Use document.URL to get current url and get last word with regex

var url = document.URL;
var match = url.match(/([^/]*)$/);

console.log(url);
console.log(match);

document.getElementById("username19").value = match[1];
<label for="username19" >Name</lable>
<input name="username" id="username19" type="text" value="">
0

You can try like as -

JavaScript :

function ReplaceHash(){
    var url       = window.location.pathname;      /*URL without HASH*/
    var hash      = window.location.hash;          /*Only Hash URL*/
    var lastWord  = hash.split('/');
    lastWord[(lastWord.length)-1] = 'username19';  /*Put your text here*/
    hash          = lastWord.join('/');
    url           = url + hash;                    /*Your New URL*/
    return url;
}

var newUrl = ReplaceHash();
console.log(newUrl);
Sumon Sarker
  • 2,707
  • 1
  • 23
  • 36
0

This loads after input element is loaded. But you can bind it to an event.

$('input').load('input', function () {
  var str = window.location.pathname.split("/");         
  var res = str[str.length-1];
  document.getElementById("username19").setAttribute("value", res);
  console.log(res);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Name</lable>
<input name="username" id="username19" type="text" value="">
Rüzgar
  • 947
  • 9
  • 20