Domanda

I am using the YUI3 library and am using a filter to match and replace parts of a URL.

Because filter is not very flexible, I am only able to provide a regex expression for searching and then a string for replacing the matches:

filter: {
    searchExp : "-min\\.js",
    replaceStr: "-debug.js"
}

In my case, I have a URL that looks like this:

http://site.com/assets/js?yui-3.9.0/widget-base/assets/skins/sam/widget-base.css&yui-3.9.0/cssbutton/cssbutton-min.css

I would like to match /assets/js if there are .css files. If the parameters contain a CSS file, then it will always only contain CSS files.

So far, I have written a small regex to check for the presence of .css at the very end:

.*\.css$

However, now, if we have a match, I would like to return /assets/js as the match. Is this something that is doable with regex?

Personally, I would rather this be done with a simple function and a simple if/else, but due to the limitations (I can only use regex), I need to find a regex solution to this.

È stato utile?

Soluzione

This is a bit hacked together, but should do the job:

var t = new RegExp( "/assets/js(([^\\.]*\\.)*[^\\.]*\\.css)$" )

document.write( "http://site.com/assets/js?yui-3.9.0/widget-base/assets/skins/sam/widget-base.css&yui-3.9.0/cssbutton/cssbutton-min.css".replace( t, "/newthing/$1" ) );

Essentially it searches for /assets/js, followed by any characters, followed by .css. If the whole thing matches it wil replace it with the new text, and include the matched pattern (from the first brackets) after it. Everything from before /assets isn't included in the match, so doesn't need to be included.

I imagine your library uses replace internally, so those strings should work. Specifically,

"/assets/js(([^\\.]*\\.)*[^\\.]*\\.css)$"
"/newthing/$1"

I'm not quite sure what you want to do with the results, but this allows you to change the folder and add suffixes (as well as check for the presence of both tokens in the first place). To add a suffix change the replacement to this:

"/assets/js$1-mysuffix"
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top