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

2
  • [&|''|""|>|<] is not valid - you can't alternate inside a character class Commented Apr 6, 2017 at 13:38
  • Interesting, but not getting the result you are expecting and for what? May be there is some more easy way Commented Apr 6, 2017 at 13:41

2 Answers 2

1

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 "));

Sign up to request clarification or add additional context in comments.

Comments

0

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 "));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.