简体   繁体   中英

Execute function if url does not contain a string from array

I'm trying run a script if URL doesn't contain specific string. Here is what i have so far:

var ignorePages = ['page1','page2','page3'];

if (window.location.href.indexOf($.inArray(ignorePages)) === -1) {
    // do something
}

But this is not working. I would like to test if the string is found in array and if not, execute. Searched the SO Q/A but couldnt find a solution via array using jQuery's inArray .

You can do this easily with underscore . I also think you may want to use location.pathname instead of location.href . Anyhow, this is how I would do it.

import { contains } from 'underscore';

let blacklist = ['/splash', '/login', '/feed' ];

if (! contains(blacklist, window.location.pathname) {
  /* do stuff here */
}

Thanks all for pointing in right directions. I've solved it with correct usage of inArray:

var ignorePages = ['/page1','/page2','/page3'];
var currentUrl = window.location.pathname;

if ($.inArray(currentUrl, ignorePages) === -1) {
    // do something
}

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