Ad

Using Capture Group $1 To Access Object's Key Value

- 1 answer

aBelow, I am trying to access the HTML entity value, which is stored in the object as shown below by defining the key using regular expressions. However, I get "Batman undefined Robin" as opposed to "Batman & Robin". Could somebody explain to me why i am getting undefined as opposed to the object's key value property? Thank you!

function convertHtmlEntities ( str ) {

    // Object containing all the key value pair of HTML entities.
    var htmlEntities = {
        "&": "&",
        "<": "&lt;",
        ">": "&gt;",
        '"': "&quot;",
        "'": "&apos;"
    };

    // Regular expression for replacing the items mentioned above with the
    // appropriate HTML entities.
    console.log( str.replace( /([\&\<\>\"\'])+/, htmlEntities['$1'] ) );
    return str.replace( /([\&\<\>\"\'])+/, "$1" );
}

convertHtmlEntities("Batman & Robin"); // Should return "Batman &amp; Robin"
Ad

Answer

You can pass a function to String.replace():

str.replace( /([\&\<\>\"\'])+/, function(match){
    return htmlEntities[match];
});
Ad
source: stackoverflow.com
Ad