[英]How can I set an HTML element's ID to equal its inner text with JS/jQuery?
[英]How to Strip off HTML Element and its Inner Text Using Jquery
我试图通过替换标记来替换内联脚本注入,然后我想删除整个标记及其内部文本。 我正在努力删除整个标签。 任何帮助都会非常有用。 这是我能够实现的-
$(".txtScript").live("blur", function () { stripScriptTags(); }); function stripScriptTags() { var wrappedString = $(".txtScript").val(); var noScript = wrappedString.replace(/script/g, "THISISNOTASCRIPTREALLY"); var html = $(noScript); html.find('THISISNOTASCRIPTREALLY').remove(); }
我传递的输入是-
<table> <tr> <td>Test</td> <td><script type="Text/JavaScript">alert('hello')</script>Success</td> </tr> </table>
预期产出-
<table> <tr> <td>Test</td> <td>Success</td> </tr> </table>
你不需要.replace(/script/g)
与 jQuery。 但是,如果您更喜欢 RegExp,请考虑将i
标志与g
用于不敏感的大小写。
此外,jQuery 添加了一些额外的标签,例如<tbody>
并且它比 RegExp 更慢。 我不推荐这种方式。
仅 jQuery:
$('.txtScript').on('blur', stripScriptTags); function stripScriptTags() { var wrappedString = $(this).val(); var $html = $(wrappedString); $html.find('script').remove(); $('#result').text($html[0] && $html[0].outerHTML || ''); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <textarea cols="30" rows="10" class="txtScript"></textarea> <pre id="result"></pre>
使用正则表达式:
$('.txtScript').on('blur', stripScriptTags); function stripScriptTags() { const regex = /\\<script(.*)\\/script\\>/gi; $('#result').text($(this).val().replace(regex, '')); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <textarea cols="30" rows="10" class="txtScript"></textarea> <pre id="result"></pre>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.