如果 URL 中的日期晚于当前月份,则重定向

如果今天的日期是当前日期或过去日期,我试图通过读取当前页面 URL 并查找关键字来显示页面。例如,


示例网址:http : //www.website.com/blog/2019/october.html


我想编写一个脚本,从页面的 URL 中找到月份(“十月”)和年份(2019),并确定它是当前的还是过去的。如果是在未来,它会将它们重定向到错误页面,当前或过去将让它们通过。这样做的目的是我正在预发布页面,我不希望用户在它是当前内容之前能够访问这些页面。


我目前正在使用 window.location.href.includes 在 URL 中查找值,然后使用循环与数组进行比较以返回月份和年份数字。到目前为止我的代码:


// Sample URL: http://www.website.com/blog/2019/october.html


var monthName = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];

var monthNum = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];


for (i = 0; i < monthName.length; i++) {

    if (window.location.href.includes(monthName[i]) > 0) {

        var pageMonth = (monthNum[i]);

    }

    else {

    }

}

这会给我 10 的结果。然后我打算对年份做同样的事情,然后再做一个将它们组合成一个日期的语句,然后使用另一个语句来确定 thatDate <= currentDate。有没有更好的方法来执行这个?


这种方法一团糟,似乎我可能遗漏了一些使这更容易实现的东西。


更新:感谢您的所有回复。我已经完成了我的代码,这仍然是可取的,因为它不依赖于 URL 的结构,相反,它只会搜索所有内容,以防我需要移动文件或在其他地方进行这项工作。我认为它肯定可以使用一些清理(尤其是两位数的月份部分),但我想在这里发布它。


var d = new Date();

var monthTwoDigit = ("0" + (d.getMonth() + 1)).slice(-2);

var monthName = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];

var monthNum = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];


for (i = 00; i < monthName.length; i++) {

    if (window.location.href.includes(monthName[i]) > 0) {

        var pageMonth = monthNum[i];

    }

    else {

    }

}


for (i = 2019; i < 3000; i++) {

    if (window.location.href.includes(i) > 0) {

        var pageYear = (i);

    }

    else {

    }

}


var urlDate = "" + pageYear + pageMonth;

var actualDate = "" + d.getFullYear() + monthTwoDigit;


if (urlDate > actualDate) {

    window.location.replace("http://www.website.com/error.html");

}

else {

    document.write("SAFE");

}


绝地无双
浏览 190回答 3
3回答

ibeautiful

是的,可以通过多种方式改进此代码。此外,为了比较日期,我们将使用Date实例,这是处理日期和时间的内置 JS 方法。var monthName = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];首先,我们不需要列出月份数字,因为我们可以使用上面数组的数组索引(从 0 到 11),它将给我们带来好处。现在让我们从 URL 解析月份和年份。我们将使用正则表达式来编写更少的代码:const matches = window.location.href.match(/http:\/\/www.website.com\/blog\/([0-9]{4})\/([a-z]{3,})\.html/);// String.prototype.match, which we used can give us null value if URL doesn't match our pattern, so we need to check it first.&nbsp;if (matches !== null) {&nbsp; const year = parseInt(matches[0]); // the first match of regular expression is the year&nbsp; const monthIndex = monthName.indexOf(matches[1]); // this should give us the number of month, from 0 to 11&nbsp; if (monthIndex !== -1) { // but we must continue only if month name in the URL is correct.&nbsp; &nbsp; const date = new Date(); // Get current date.&nbsp; &nbsp; // Now let's extract month and year from the current date.&nbsp; &nbsp; // date.getMonth() returns the current number of month from 0 to 11, just what we need.&nbsp; &nbsp; // date.getFullYear() obviously returns the current year number.&nbsp; &nbsp; // Let's use these methods and compare current date values with ones we've got from the URL:&nbsp; &nbsp; if (date.getFullYear() > year || (date.getFullYear() === year && date.getMonth() > monthIndex)) {&nbsp; &nbsp; &nbsp; // we're in the future, let's redirect:&nbsp; &nbsp; &nbsp; window.location.href = 'https://website.com/error.html';&nbsp; &nbsp; }&nbsp; }}

小唯快跑啊

我会像你指定的那样做。清晰、明显的逻辑是最容易维护的。function isFutureURL(url) {&nbsp; // Month name array&nbsp; let months = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];&nbsp; // Parse the URL for the year and month&nbsp; let b = url.split(/\/|\./);&nbsp; let y = b[6];&nbsp; let m = months.indexOf(b[7]);&nbsp; // Set URL date to 00:00:00 at start of URL month&nbsp; let urlDate = new Date(y, m, 1);&nbsp; // Return true if test date is after current date&nbsp; // I.e. it's the first of next month or greater&nbsp; return urlDate > Date.now();}['http://www.website.com/blog/2018/april.html',&nbsp;'http://www.website.com/blog/2019/october.html',&nbsp;'http://www.website.com/blog/2020/may.html'].forEach(sampleURL =>&nbsp;&nbsp; console.log(sampleURL + '\n is in the future? ' + isFutureURL(sampleURL)));这假设月份和年份将始终位于 URL 中的同一位置,您可能需要考虑使之更可靠的选项(例如,在 URL 的任何位置查找月份名称和有效年份)。您可能还想对 URL 以及y和m 的值进行一些验证,以避免用户看到错误。

米琪卡哇伊

使用 if 条件例如,让来源为:http : //www.website.com/blog/2019/october.html获取 currMonthNo 和 curryear 从var d = new Date();并同时获得srcMonthNo从sourceurl现在检查if(source.indexof(curryear) > -1 && currMonthNo <= srcMonthNo) {&nbsp; // Then return your conditional code} else {&nbsp; // Return error message}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript