javascript - RegExp : How to replace the second occurrence using object? -


function converthtml(str) {   var obja={'&':'&​amp;','<':'&​lt;','>':'&​gt;','\'':'&​apos;','"':'\&​quot;'}   var matchstr = str.match(/([&|''|""|>|<])/g)   var matchstr1=''   for(var i=0; i<matchstr.length; ++i){       matchstr1 = str.replace(matchstr[i], obja[matchstr[i]])    }   return matchstr1; }  console.log(converthtml("hamburgers < pizza < tacos ")); 

output i'm getting hamburgers &​lt; pizza < tacos. want hamburgers &​lt; pizza &​lt; tacos. possible replace second occurrence using code changes ?.

i suggest use following approach.

var objmap = {             // ===> object specified keys    '&': '&​amp;',            // ===> have replaced    '<': '&​lt;',             // ===> corresponding values    '>': '&​gt;',    '\'': '&​apos;',    '"': '\&​quot;'  }    function converthtml(str) {    var res = str.replace(/[&<>\\"]/g, match => objmap[match]);    return res;  }    console.log(converthtml("hamburgers < pizza < tacos "));


Comments

Popular posts from this blog

inversion of control - Autofac named registration constructor injection -

verilog - Systemverilog dynamic casting issues -

ios - Change Storyboard View using Seague -