Reputation: 3285
I am looping through an array of letters and am trying to find only &, <, >, " and ' characters to replace them with their HTML entities...
Here is my code
function convertHTML(str) {
// html entity switch block
function entify(char){
alert(char);
switch (char) {
case '&':
return '&';
case '<':
return '<';
case '>':
return '>';
case '"':
return '"';
case '\'':
return ''';
}
}
// convert string into an array
str = str.split('');
// loop through the array
for (var i = 0; i < str.length; i++) {
// compare each to the regular expression, if it matches then it needs to be replaced with an html entity
console.log(str[i]);
str[i] = str[i].replace(/[&<>"']/g, entify);
}
str = str.join('');
console.log(str);
return str;
}
convertHTML("&");
Unfortunately my regular expression doesn't seem to be picking up the characters and I'm not even triggering the entify
function.
Why is that?
Upvotes: 1
Views: 150
Reputation: 22776
Use this (which calls entify for each match using an arrow function) :
function convertHTML(str) {
// html entity switch block
function entify(char){
switch (char) {
case '&':
return '&';
case '<':
return '<';
case '>':
return '>';
case '"':
return '"';
case '\'':
return ''';
}
}
// convert string into an array
str = str.split('');
// loop through the array
for (var i = 0; i < str.length; i++) {
// compare each to the regular expression, if it matches then it needs to be replaced with an html entity
str[i] = str[i].replace(/[&<>"']/g, (a) => entify(a) );
}
str = str.join('');
console.log(str);
return str;
}
convertHTML("Hello, World! It's \">_<\" great to be here & live.");
// => "Hello, World! It's ">_<" great to be here & live."
Upvotes: 2
Reputation: 91385
Call entify
as a callback:
function convertHTML(str) {
// html entity switch block
function entify(char){
// alert(char);
switch (char) {
case '&':
return '&';
case '<':
return '<';
case '>':
return '>';
case '"':
return '"';
case '\'':
return ''';
}
}
// convert string into an array
str = str.split('');
// loop through the array
for (var i = 0; i < str.length; i++) {
// compare each to the regular expression, if it matches then it needs to be replaced with an html entity
//console.log(str[i]);
str[i] = str[i].replace(/[&<>"']/g, function(m) {return entify(m);});
// here ___^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
str = str.join('');
return str;
}
console.log(convertHTML(">"));
Upvotes: 2