简体   繁体   English

正则表达式替换标签中的字符

[英]regex replace characters within tags

I'm already using a html parser, but I need to create a regex that will select the < and > symbols within the first instance of <code> tags - in this case, the one with the class "html". 我已经在使用html解析器,但是我需要创建一个正则表达式,它将在<code>标记的第一个实例内选择<和>符号-在这种情况下,将使用类“ html”。

    <code class="html">
        <b>test</b><script>lol</script>
            <code>test</code> <b> test </b>
        <lol>
                        </lol>

            <test>
    </code>

So every < or > within the indented area starting from <b> to the start of the last </code> should be replaced, leaving the outer <code> tags alone. 因此,应该替换从<b>到最后一个</code>开头的缩进区域中的每个<或>,而不要使用外部的<code>标记。

I'm using javascript's .replace method and would like all < and > symbols within the code area to turn into ascii &#60; 我正在使用javascript的.replace方法,并且希望代码区域内的所有<和>符号都变成ascii&#60; and &#62;. 和&#62;。

I imagine its best to use a look forward/back regex using $1 etc. but can't figure out where to begin, so any help would be much appreciated. 我想最好使用$ 1等使用前向/后向正则表达式,但不知道从哪里开始,因此,我们将不胜感激。

How about something like this? 这样的事情怎么样? In this example I'm creating a variable and populating the variable with html, just to get things started 在此示例中,我将创建一个变量,并使用html填充该变量,以使事情开始。

var doc = document.createElement( 'div' );
doc.innerHTML =  ---your input html here

Here I'm pulling the code tag 在这里我拉代码标签

var string = doc.getElementsByTagName( 'code' ).innerHTML; 

Once you have the string then simply replace the desired brackets with 有了字符串后,只需将所需的括号替换为

var string = string .replace(/[<]/, "&#60;)
var string = string .replace(/[>]/, "&#62;)

then just reinsert the replaced value back into your source html 然后只需将替换后的值重新插入到源html中

The easy way: 简单的方法:

var elem = $('.html');
elem.text(elem.html());

This will not necessarily use literally &#60; 这不一定会在字面上使用&#60; for escaping; 逃跑 if you're fine with a different escape, it's much simpler than anything else you can do, though. 如果您可以使用其他转义符,那么它比您可以做的任何其他事情都简单得多。

If you have multiple elements like that, you might need to wrap the second line in an elem.each() ; 如果您有多个类似的元素,则可能需要将第二行elem.each() otherwise the html() method will probably just concatenate the content from all elements or something similarly pointless. 否则, html()方法可能只会连接所有元素中的内容或类似的毫无意义的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM