views:

26

answers:

1

So, I have to determine page type in a proprietary CRM, using JavaScript. The only way to determine the page type (that is, the only consistent difference on the front end) is by examining a script tag (out of many list) whose src attribute begins with /modules/.

In a list of a dozen or so script tags in the header, each page has a line of the following format

 <script src="/modules/example/includes/sample.js" type="text/javascript"></script> 

Now, the order of the script tag is never the same, but, there's always one script that has /modules/blah. I need to extract blah to my script can detect what kind of page it is.

So, how do I, using either JavaScript or jQuery, extract the script tag's src value, where src begins with /modules, and store the value after that ('example', in the example above) as a javascript variable?

+1  A: 

Well, you can start by collecting all of the script elements. With jQuery, that's as simple as

var scripts = $("script");

Then limit that set to the elements that have a src attribute:

var scripts = $("script[src]");

...and further limit it to those with a src attribute beginning with "/modules/":

var scripts = $("script[src^='/modules/']");

...which given your description should result in a set of exactly one element, from which you can now pull the src attribute value itself:

var path = $("script[src^='/modules/']").attr('src');

Ok, that was easy - now to extract the next part of the path. There are plenty of ways to do this, but split is quick & dumb: create an array of parts using '/' as the separator, then pick off the third element (which will be the one after "modules"):

var pathPart = $("script[src^='/modules/']").attr('src').split('/')[2];

Obviously, this is all very specific to the exact format of the script path you're using as an example, but it should give you a good idea of how to begin...

Shog9
Thanks! I just got to the third example myself; needed held to get over the hump for the last one.
yc
@yc: I've expanded on it a bit...
Shog9