开发者

Extract src attribute from script tag and parse according to particular matches

开发者 https://www.devze.com 2023-01-06 07:09 出处:网络
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 ta

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?


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...

0

精彩评论

暂无评论...
验证码 换一张
取 消