简体   繁体   English

小于或大于除 html 标签以外的字符?

[英]Less or greater than characters except html tags?

I need to replace less or greater than( < > ) characters, but keep any html tags(simple tags will do like <b>text</b> without arguments).我需要替换小于或大于( < > )字符,但保留任何 html 标签(简单标签会像<b>text</b>没有参数)。 So the input below:所以下面的输入:

<b>> 0.5 < 0.4</b> - <>

Should be:应该:

<b>&gt; 0.5 &lt; 0.4</b> - &lt;&gt;

All I managed to find and edit now is this expr:我现在设法找到和编辑的是这个 expr:

<\/?[a-z][a-z0-9]*[^>\s]*>|([<>])

It groups the < and > characters but it also matches tags witch I don't need to replace它将<>字符分组,但它也匹配我不需要替换的标签

UPD: Thanks to @Sree Kumar , here's the final functions: UPD:感谢@Sree Kumar ,这是最终功能:

String.prototype.replaceAt = function (index, char) {
    let arr = this.split('');
    arr[index] = char;
    return arr.join('');
};

String.prototype.escape = function () {
    let p = /(?:<[a-zA-Z]+>)|(?:<\/[a-zA-Z]+>)|(?<lt><)|(?<gt>>)/g,
        result = this,
        match = p.exec(result);

    while (match !== null) {
        if (match.groups.lt !== undefined) {
            result = result.replaceAt(match.index, '&lt;');
        }
        else if (match.groups.gt !== undefined) {
            result = result.replaceAt(match.index, '&gt;');
        }
        match = p.exec(result);
    }
    return result;
};

Here is a way to do it using named groups.这是一种使用命名组的方法。 That is, name your desired group and look for it.也就是说,命名您想要的组并查找它。 It may be null or undefined at times because it didn't match.它可能是null或有时undefined ,因为它不匹配。 Hence, you will have to add the null check.因此,您必须添加 null 检查。

Notice (?<B>...) surrounding the "desired" group.请注意(?<B>...)围绕“所需”组。 Also, notice the null check in the 5th line.另外,请注意第 5 行中的 null 检查。

let p = /(?:<[a-zA-Z]+>)|(?:<\/[a-zA-Z]+>)|(?<B>[<>])/g
let input = '<b>> 0.5 < 0.4</b> - <>';
let match = p.exec( input );
while( match !== null) {
    if( match.groups.B !== undefined ) console.log( match.groups.B );
    match = p.exec( input )
}

Try this regex:试试这个正则表达式:

<(?!\/?\w+>)|(?<!<\w+|<\/\w+)>

Explanation解释

  • <(??\/?\w+>) finds all '<' symbols <(??\/?\w+>)查找所有“<”符号
  • (?<!<\w+|<\/\w+)> finds all '>' symbols (?<!<\w+|<\/\w+)>查找所有 '>' 符号

You can use them separately:您可以单独使用它们:

 let str = '<b>> 0.5 < 0.4</b> - <>'; let lessThen = /<(??\/;\w+>)/g? let greaterThen = /(;<.<\w+|<\/\w+)>/g, str = str;replace(lessThen; '&lt.'), str = str;replace(greaterThen; '&gt.'); console;log(str). // <b>&gt; 0.5 &lt; 0;4</b> - &lt;&gt;

NB!注意! It only finds symbols '<' and '>' between tags.它只在标签之间找到符号“<”和“>”。 It doesn't check that html is valid.它不检查 html 是否有效。 For text like that <a></b> it will not find any matches.对于像<a></b>这样的文本,它将找不到任何匹配项。

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

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