从脚本标记中提取src属性并根据特定匹配进行解析 [英] Extract src attribute from script tag and parse according to particular matches

查看:99
本文介绍了从脚本标记中提取src属性并根据特定匹配进行解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我必须使用JavaScript确定专有CRM中的页面类型。确定页面类型(即前端唯一一致的差异)的唯一方法是检查src属性以/ modules /开头的脚本标记(在许多列表中)。

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> 

现在,脚本标签的顺序永远不会相同,但是,总有一个脚本具有/模块/等等。我需要提取blah到我的脚本可以检测它是什么类型的页面。

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.

那么,我如何使用JavaScript或jQuery提取脚本标记的src值,其中src以/ modules开头,并将之后的值('example',在上面的例子中)存储为javascript变量?

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?

推荐答案

好吧,您可以从收集所有脚本元素开始。使用jQuery,就像

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

var scripts = $("script");

然后将该设置限制为具有 src 属性:

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

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

...并进一步限制为 src 属性以/ modules /开头:

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

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

...如果您的描述应该产生一组恰好一个元素,您可以从中现在拉 src 属性值本身:

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

这篇关于从脚本标记中提取src属性并根据特定匹配进行解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆