简体   繁体   English

替换javascript正则表达式中的标签

[英]replace tags in javascript regexp

I am doing an REGEXP tool, that accepts input in text and showing the results in a div. 我正在做一个REGEXP工具,该工具接受文本输入并在div中显示结果。 I replace the matches with a <b>Match</b> when show results. 显示结果时,我用<b>匹配</ b>替换匹配项。 If it matches raw text it works fine but the problem is when insert HTML code 如果它与原始文本匹配,则可以正常工作,但问题是在插入HTML代码时

I want to replace all tags except <b> tag with html entities, how can achieved that? 我想用HTML实体替换除<b>标记之外的所有标记,如何实现?

 var regExpTool = {
    makeRegexp: function(pattern, opts){
        var regexp = new RegExp(pattern, opts);
        return regexp;
    },
    createResults: function(pattern, string, opts){
        var res = string.replace(this.makeRegexp(pattern, opts), "<b>$&</b>")

        results.style.display = "block";
        text.style.display = "none";
        results.innerHTML = res;
  }
}

Perhaps your code should look more like: 也许您的代码应该更像:

var win = window, doc = document, bod = doc.getElementsByTagName('body')[0];
function E(e){
  return doc.getElementById(e);
}
function regExpTool(text, outputElement){
  this.makeBold = function(options){
    outputElement.innerHTML = text.replace(new RegExp('^(<.+>)*('+text+')(<\/.+>)*$', options), '<b>$2</b>')
    outputElement.style.display = 'block';
   };
}

new regExpTool('<div>now</div>', E('wow')).makeBold();

Note, that there is no reason for your makeRegexp method. 请注意,没有makeRegexp方法。

Here's the http://jsfiddle.net/PHPglue/FjEdg/2/ . 这是http://jsfiddle.net/PHPglue/FjEdg/2/

It won't work with self closing tags. 它不能与自闭标签一起使用。

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

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