I'm working on a hash system for a website I'm making, although some of the pages I want to hash require a PHP id at the end. I don't want to have .php in the hash url so I'm trying to split it so I can insert it later on.
An example of what is on the html side.
<a href="#!/_radio/profile?id=3">link</a>
This is what I have so far. It all works except the extra variable isn't included at the end.
var Radio = {};
Radio = {
_jsInit: function () {
$(window).bind('hashchange', function () {
Radio._currentPage();
Radio.loadPage(Radio._PageName, Radio._extra)
});
$(window).trigger("hashchange")
},
_currentPage: function () {
this._PageName = location.hash.replace('#!/', '');
if (this._PageName == "") window.location = "#!/_radio/home";
this.values = this._PageName.split("?");
this._extra = this.values[1];
},
loadPage: function (page, extra) {
$('#content').fadeOut(200).load('_files/_v2/_pages/' + page + '.php?' + extra + '', function () {
$('#content').fadeIn(400)
});
},
};
$(document).ready(function () {
Radio._jsInit();
});
For this before and after:
Before: "#!/_radio/profile?id=2"
After: "_files/_v2/_pages/profile.php?id=2"
You can use a regex to find the parts of the string you want:
function convertStr(str) { var matches = str.match(/(\\/[^\\/]+)(\\?.*$)/); return "_files/_v2/_pages" + matches[1] + ".php" + matches[2]; } // call the function and display the result in the snippet var result = convertStr("#!/_radio/profile?id=2"); document.write(result);
Or, any even simpler version that uses .replace()
:
function convertStr(str) { return str.replace(/(^.*)(\\/[^\\/]+)(\\?.*$)/, "_files/_v2/_pages$2.php$3"); } // call the function and display the result in the snippet var result = convertStr("#!/_radio/profile?id=2"); document.write(result);
After playing around with the code jfriend00 provided, I got it working.
var Radio = {};
Radio = {
_jsInit: function () {
$(window).bind('hashchange', function () {
Radio._currentPage();
Radio.loadPage(Radio._PageName)
});
$(window).trigger("hashchange")
},
_currentPage: function () {
this._PageName = location.hash.replace('#!/', '');
if (this._PageName == "") window.location = "#!/_Radio/home";
},
loadPage: function (page) {
var matches = page.split("?");
var load = "_files/_v2/_pages/" + matches[0] + ".php?" + matches[1];
$("#content").fadeOut(200).load(load, function () {
$("#content").fadeIn(400)
});
},
};
$(document).ready(function () {
Radio._jsInit();
});
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.