简体   繁体   中英

cut off last few characters of values passed with JavaScript split function

I have Javascript code passing start and end timedate values from a previous page, however, the start value contains additional characters which are not needed. Is there a way in which I can shave off the unnecessary characters?

The URL of in the search bar when forwarded is localhost:56363/Bookings.aspx#start=27/02/2018 12:30&end=27/02/2018 17:30 and the &end is passed to the start input box but not needed. The JavaScript code is as follows:

 <script type="text/javascript"> $(document).ready(function () { hash(); function hash() { var hashParams = window.location.hash.substr(1).split('#'); for (var i = 0; i < hashParams.length; i++) { var p = hashParams[i].split('='); document.getElementById("<%=start.ClientID%>").value = decodeURIComponent(p[1]); } var hashParams = window.location.hash.substr(1).split('&'); for (var i = 0; i < hashParams.length; i++) { var p = hashParams[i].split('='); document.getElementById("<%=end.ClientID%>").value = decodeURIComponent(p[1]);; } } }); </script> 

Hash parameters?! What!

Most apps will use query parameters with a url that looks like localhost:56363/Bookings.aspx?start=27/02/2018 12:30&end=27/02/2018 17:30 notice the ? instead of a hash. Query parameters would be available as window.location.search

Anyway. Change your hash() function to

function hash(){
    var hash = window.location.hash;

    var start = hash.match(/start=([^&]+)/)[1];
    document.getElementById("<%=start.ClientID%>").value = decodeURIComponent(start);

    var end = hash.match(/end=([^&]+)/)[1];
    document.getElementById("<%=end.ClientID%>").value = decodeURIComponent(end);
}

The regular expressions will find the relevant parameters and the capture group ([^&]+) will capture the value of each parameter. We then use the [1] to retrieve the value of each parameter.

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