简体   繁体   中英

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 is Hamburgers &​lt; Pizza < Tacos Hamburgers &​lt; Pizza < Tacos . I want Hamburgers &​lt; Pizza &​lt; Tacos Hamburgers &​lt; Pizza &​lt; Tacos Hamburgers &​lt; Pizza &​lt; Tacos . So is it possible to replace the second occurrence using this code with some changes ?.

I would suggest you to use following approach.

 var objMap = { // ===> object with specified keys '&': '&​amp;', // ===> that have to be replaced '<': '&​lt;', // ===> with their corresponding values '>': '&​gt;', '\\'': '&​apos;', '"': '\\&​quot;' } function convertHTML(str) { var res = str.replace(/[&<>\\\\"]/g, match => objMap[match]); return res; } console.log(convertHTML("Hamburgers < Pizza < Tacos ")); 

The issue is in line:

matchStr1 = str.replace(matchStr[i], objA[matchStr[i]])

In each iteration "str" is always the same.

Your code fixed:

function convertHTML(str) {
  var objA={'&':'&​amp;','<':'&​lt;','>':'&​gt;','\'':'&​apos;','"':'\&​quot;'}
  var matchStr = str.match(/([&|''|""|>|<])/g);
  for(var i=0; i<matchStr.length; ++i){
     str = str.replace(matchStr[i], objA[matchStr[i]])
  }
  return str;
}
console.log(convertHTML("Hamburgers < Pizza < Tacos "));

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