[SOLVED] Replace the second occurrence of symbols " & < > '

[SOLVED] Replace the second occurrence of symbols " & < > '
0

#1

How can i replace the second occurrence of the symbols ?? Once it hits the first symbols, it replaces it but how i can reach the symbols after it ??


function convertHTML(str) {
  // &colon;&rpar;
   var charToHtml = {
        '&' : '&amp;',
        '<' : '&lt;',
        '>' : '&gt;',
        '"' : '&quot;',
        "'" : '&apos;'
      };

  for (var char in charToHtml) { 
    if (str.includes(char)){
     str = str.replace(char, charToHtml[char]);
    }
    
    //console.log(char +" "+charToHtml[char]);
  }
  
  return str;
}

convertHTML("Hamburgers < Pizza < Tacos");


#2

Using regular expressions instead of strings as the first argument for .replace allows you to replace multiple instances of a match.


#3
if (str.includes(char)){
      rp = '/'+ char + '/g';
      console.log(rp);
      str = str.replace(rp, charToHtml[char]);
      console.log(str)
    }

it is returning the string untouched


#4

You can’t construct regex by putting together strings like that. Use the RegExp constructor instead:

rp = new RegExp(pattern, flags);

#5

The problem you have is that to replace all occurrences, you have to use the g regex flag. But you’re not using regex, you’re just selecting a string, so you don’t have access to that. As a result, you’ll just replace the first instance.

You can do a number of things to fix. One option is described above. Another option is to loop through the string rather than the dictionary, then just check each character in turn, replacing if they need replacing. It allows you to avoid using replace completely if you set it up right as well.


#6

This is the solution:


function convertHTML(str) {
  // &colon;&rpar;
   var charToHtml = {
        '&' : '&amp;',
        '<' : '&lt;',
        '>' : '&gt;',
        '"' : '&quot;',
        "'" : '&apos;'
      };
  var rp= '';

  for (var char in charToHtml) { 
    if (str.includes(char)){
      rp = new RegExp ( char , 'g');
      str = str.replace(rp, charToHtml[char]);
    }
 }
  
  return str;
}

convertHTML("Hamburgers < Pizza < Tacos");

#7

I found this chapter here (https://eloquentjavascript.net/09_regexp.html) helped me much better understand the full structure/possibilities of RegEx than was as described in the course materials.


#8

Thank you i will definitely check it :+1: