简体   繁体   中英

JavaScript .search() for a URL with wildcard using RegEx

I'm building a site that is a portfolio of projects. I have some pagination that allows you to go next/previous project.

I want to run some animations when coming to a project, but not when browsing between projects.

My plan is to use the referrer URL to know if you came to a project from another project, and thus not run the animation. But my RegEx is not good, so I'm having trouble.

Here is what I'd like to do (pseudo code)

var refURL = document.referrer;
if( refURL.search('http://www.example.com/work/digital/*') > 0 ) {
    // Do not run animation
} else {
    // Run animation
}

The important thing, is that "http://www.example.com/work/digital/" should be FALSE, but "http://www.example.com/work/digital/*" should be TRUE.

So, what's the RegEx to do that?

Thanks!

I think you are looking for this:-

var refURL = document.referrer;
if( refURL.search('http://www.example.com/work/digital/(.*)') > 0 ) {
    // Do not run animation
} else {
    // Run animation
}

In other way, you can use indexOf()

refURL.indexOf("http://www.example.com/work/digital/");

if(refURL.indexOf("http://www.example.com/work/digital/") > -1) {
       // Do Your Stuff
}

(.*) matches 0 or more characters whereas (.+) matches 1 or more characters

Also RegExp in JavaScript does not need to be enclosed, so just type

var exp = /pattern/modifiers

For more details visit: http://www.w3schools.com/jsref/jsref_obj_regexp.asp

My idea for your problem is to try something like:

var refURL = document.referrer;
if (refURL.search(/^http:\/\/www.example.com\/work\/digital\/(.+)$/i) >= 0) {
    // Do not run the animation
} else {
    // Run the animation
}

can use regex and in javascript

var searchin = item.toLowerCase();
var str = "*abc*";
str = str.replace(/[*]/g, ".*").toLowerCase().trim();
return new RegExp("^"+ str + "$").test(searchin);
var re = /^http:\/\/www.example.com\/work\/digital\/.+$/i;
console.log('http://www.example.com/work/digital/x'.search(re));
console.log('http://www.example.com/work/digital/'.search(re));

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