可以让RegEx仅匹配某些字符/ [&<>"'] / g

时间:2017-09-02 11:47:13

标签: javascript regex

我正在循环查看一系列字母,并且我只想找到&,<,>,"和'用HTML实体替换它们的字符......

这是我的代码

function convertHTML(str) {

    // html entity switch block
    function entify(char){
        alert(char);
        switch (char) {
            case '&':
                return '&​amp;';
            case '<':
                return '&​lt;';
            case '>':
                return '&​gt;';
            case '"':
                return '&​quot;';
            case '\'':
                return '&​apos;';
        }
    }


    // 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函数。

为什么?

2 个答案:

答案 0 :(得分:2)

使用此(使用箭头功能调用每个匹配的内容):

function convertHTML(str) {
    // html entity switch block
    function entify(char){
        switch (char) {
            case '&':
                return '&​amp;';
            case '<':
                return '&​lt;';
            case '>':
                return '&​gt;';
            case '"':
                return '&​quot;';
            case '\'':
                return '&​apos;';
        }
    }

    // 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&​apos;s  &​quot;&​gt;_&​lt;&​quot;  great to be here &​amp; live."

答案 1 :(得分:2)

entify称为回调:

function convertHTML(str) {

    // html entity switch block
    function entify(char){
       // alert(char);
        switch (char) {
            case '&':
                return '&​amp;';
            case '<':
                return '&​lt;';
            case '>':
                return '&​gt;';
            case '"':
                return '&​quot;';
            case '\'':
                return '&​apos;';
        }
    }


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