javascript - RegExp : How to replace the second occurrence using object? -
function converthtml(str) { var obja={'&':'&','<':'<','>':'>','\'':''','"':'\"'} 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 '&': '&', // ===> have replaced '<': '<', // ===> corresponding values '>': '>', '\'': ''', '"': '\"' } function converthtml(str) { var res = str.replace(/[&<>\\"]/g, match => objmap[match]); return res; } console.log(converthtml("hamburgers < pizza < tacos "));
Comments
Post a Comment