2014-09-04 24 views
0

我有此代碼工作使用兩個正則表達式的第一次抓取任何介於<script></script>標籤之間的任何東西,無論它們是否指定了type="text/javascript"。第二種方法從其餘標籤中獲取源代碼(如果有)並創建一個要寫入的url數組。有沒有辦法用一個正則表達式來做到這一點?JavaScript的正則表達式的<腳本標記,忽略類型,但添加源,如果它存在

顯然我的類型忽略不工作。

因爲沒有人似乎閱讀或理解問題,這裏是我給的字符串。這必須轉換爲html,並附加外部js,並將內聯js添加到頁面中。我有這個工作正常,只是想做出這幾個增強。我意識到解析html不是好習慣,我已經說過了,但這是我給的任務。

var d = '<script>alert("inline javascript 1");</\script><h1>html only</h1><h2>subtitle.</h2><script>alert("inline javascript 2");</\script><script>alert("inline javascript 3");</\script><script type="text/javascript" src="http://chrismills.la/test.js"></\script><script>alert("more inline javascript");</\script><p>More Content.</p>'; 

var regInline = /<script[^type>]*>([\s\S]*?)<\/script>/gmi; 
var regSrc = /<script.*?src="(.*?)"><\/script>/gmi; 
// Extract inline javascript. 
content = content.replace(regInline, function() { 
    inline += arguments[1] + '\n'; 
}); 
// Extract external javascript urls. 
content = content.replace(regSrc, function() { 
    urls.push(arguments[1]); 
}); 
+2

[!不解析與正則表達式HTML(http://stackoverflow.com/a/1732454/2812842 ) – 2014-09-04 00:35:13

+0

好吧,我有一個字符串,其中包含html,,如何我應該遍歷字符串並將其添加到頁面? – user1572796 2014-09-04 00:39:21

+0

'document.getElementsByTagName('script')[indexhere] .innerHTML' – 2014-09-04 00:43:26

回答

0

[^type]確實不在"type"它代替否定任何字符從列表"t""y",或"p""e"否定序列。

這意味着你不應該使用[^type>]。相反,嘗試此正則表達式:

var regInline = /<script(?:(?!type).)*>(.*?)<\/script>/sgmi; 

注意[\s\S]被更換而./s ingleline修改。


瞭解更多:

相關問題