仅包含< script>来自页面源的标签 [英] Include only <script> tag from page source
问题描述
我有一个字符串,例如headData,它是<script>
,<style>
和<link>
标记的组合.对于Ex(具有虚拟数据)-
I have a string let's say headData which is a combination of <script>
, <style>
and <link>
tags. For Ex(with Dummy data) -
let headData = '<style>
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 300;
src: local('Roboto Light'), local('Roboto-Light'), url(path-to.woff) format('woff');
}</style>
<link rel="dns-prefetch" href="//assets.adobedtm.com">
<script>var isPresent = false;</script>
<script>var isContent = true;</script>
<style>@font-face {
font-family: 'Courgette';
font-style: normal;
font-weight: 400;
src: local('Courgette Regular'), local('Courgette-Regular'), url(path-to.woff2) format('woff2');}</style>'
我将整个headData注入如下标记中.
I inject whole of headData in a tag like below.
<script dangerouslySetInnerHTML={{__html: headData}} />
我不想插入与<style>, <link>
标记相关的数据之类的HTML标记,而只希望注入所有与<script>
标记相关的数据.有没有一种方法我可以使用仅选择<script>
标签的正则表达式来实现.
I don't want to inject HTML tags like <style>, <link>
tag related data and only want all the <script>
tag related data to be injected. Is there a way I can achieve this using regex of selecting only <script>
tags.
所以我最后想要注入的东西类似于-
So what I finally want to inject is similar to -
let headData = '<script>var isPresent = false;</script>
<script>var isContent = true;</script>'
用JavaScript实现此目标的正确方法是什么?
What is the right way to achieve this in Javascript?
推荐答案
您可以使用RegEx 捕获组 和match()
查找所需的标签:
You can find the wanted tags with RegEx Capturing Groups and match()
:
/(<script>)[^<>]*(<\/script>)/g
演示:
let headData = `<style>
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 300;
src: local('Roboto Light'), local('Roboto-Light'), url(path-to.woff) format('woff');
}</style>
<link rel="dns-prefetch" href="//assets.adobedtm.com" />
<script>var isPresent = false;<\/script>
<script>var isContent = true;<\/script>
<style>@font-face {
font-family: 'Courgette';
font-style: normal;
font-weight: 400;
src: local('Courgette Regular'), local('Courgette-Regular'), url(path-to.woff2) format('woff2');}</style>`;
var re = /(<script>)[^<>]*(<\/script>)/g;
headData = headData.match(re).join('\n');
console.log(headData);
这篇关于仅包含< script>来自页面源的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!