简体   繁体   中英

replace tags in javascript regexp

I am doing an REGEXP tool, that accepts input in text and showing the results in a div. I replace the matches with a <b>Match</b> when show results. If it matches raw text it works fine but the problem is when insert HTML code

I want to replace all tags except <b> tag with html entities, how can achieved that?

 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.

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

It won't work with self closing tags.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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