繁体   English   中英

在正则表达式中使用正斜杠作为匹配模式

[英]using forward slash as matching pattern in regex

我有一个textarea ,用户可以在其中键入他的代码,还有一个div标签,它可以将其显示在网页上。 我正在使用自定义标签来格式化用户代码,例如[b]bold text[/b]而不是<b>bold text </b>我正在使用string.replace()函数将自定义标签替换为原始标签,以标记预览用户代码。 但是如何使用正斜杠( / )作为匹配模式

我已经走过几个知道方法的地方。 我努力了

string.replace(/[\/b]/gi,"</b>");
string.replace(/[\x2Fb]/gi,"</b>");
string.replace(/[\x2F b]/gi,"</b>");

这是我在项目中实际执行的代码

//Helper Function
function $(id){
    return document.getElementById(id);
}
//Helper Variables//

//Display Preview of question
function render(){//
    var question_content = $("question_content").value;
    //Sanitizing data//
    var entitles = {//List of all Html entitles & custum entitles
        '<':"&lt;",
        '>':"&gt;",
        '\n':"<br>",
        '[b]':"<b>",
        '[/b]':"</b>",
        '[i]':"<i>",    
        '[/i]':"</i>",
        '[code]':"<code class='prettyprint'>",
        '[/code]':"</code>"         
    }
    question_content = question_content.replace(/<|>|\n|[b]|[\/b]/gi, function (html_ent){return entitles[html_ent];});
    //question_content = question_content.replace(/'/, "</b>");
    var preview = $("preview");
    preview.innerHTML = question_content;   
    //prettyPrint();
}

实际上,如果您不忘记转义括号,第一种方法将行得通:

string.replace(/\[\/b]/gi,"</b>");

不过,只有开头的那个应该逃脱; regex引擎足够聪明,可以将]作为文字符号和作为元符号(关闭该字符类子表达式)之间进行区分。

总的来说,您可以使用以下方法简化代码:

var codes = ['b', 'i', 'code'];
// here goes a little hack to enable special decoration for some elements
codes.code = 'class="prettyprint"';

var string = 'abc[b]abc[/b]da[code]s[/code][something]d';
string.replace(/\[(\/?)([a-z]+)]/gi, function(m, p1, p2) {
  return codes.indexOf(p2) !== -1 
  ? '<' + p1 + p2 + (!p1 && p2 in codes ? ' ' + codes[p2] : '') + '>'
  : m
});

当然可以用字典(对象)表达相同的算法,如下所示:

var decorators = { 
  b: '', i: '', 
  code: 'class="prettyprint"'
};

var string = 'abc[b]abc[/b]da[code]s[/code][something]d';
string.replace(/\[(\/?)([a-z]+)]/gi, function(m, p1, p2) {
  return p2 in decorators 
    ? '<' + p1 + p2 + 
      (!p1 && decorators[p2] ? ' ' + decorators[p2] : '') + '>'
    : m;
});

暂无
暂无

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

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