简体   繁体   English

使用RegEx的带通配符的URL的JavaScript .search()

[英]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. 但是我的RegEx不好,所以遇到了麻烦。

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. 重要的是,“ http://www.example.com/work/digital/”应为FALSE,而“ http://www.example.com/work/digital/*”应为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() 以其他方式,您可以使用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 (.*)匹配0个或多个字符,而(.+)匹配1个或多个字符

Also RegExp in JavaScript does not need to be enclosed, so just type 另外,JavaScript中的RegExp不需要包含在内,因此只需键入

var exp = /pattern/modifiers

For more details visit: http://www.w3schools.com/jsref/jsref_obj_regexp.asp 有关更多详细信息,请访问: 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 可以在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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM