我正在循环查看一系列字母,并且我只想找到&,<,>,"和'用HTML实体替换它们的字符......
这是我的代码
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("&");
不幸的是,我的正则表达式似乎没有拾取字符,我甚至没有触发entify
函数。
为什么?
答案 0 :(得分:2)
使用此(使用箭头功能调用每个匹配的内容):
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."
答案 1 :(得分:2)
将entify
称为回调:
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(">"));