Search code examples
javascriptjqueryhtmlstrip

Javascript remove HTML from Object Values


I have an array of objects and some of those object values contain HTML tags that I need to remove.

I tried looping over it and then using the jQuery function unwrap() on the element but I received an error that unwrap wasn't a function.

var tempData = w2ui.grid.records;

// Modify our tempData records to remove HTML
$.each(tempData, function(key, value) {
    value.unwrap('a');
});

My structure is as follows:

Array [ 
    Object,
    Object,
    Object
]

Example of the object/properties:

Object = {
    Name: 'Bob',
    email: '[email protected]'
    website: '<a href="http://www.example.com">Example.com</a>'
}

Desired Output after modifying object:

Object = {
    Name: 'Bob',
    email: '[email protected]'
    website: 'Example.com'
}

Here is a quick example fiddle I started: https://jsfiddle.net/zcwk1kw6/

The example shows a single value containing HTML but my end goal is to remove all HTML from any value, not targeting a specific property.

Whats the best way to approach this?


Solution

  • $.each(data, function(key, value) {
      data[key].Website = $(value.Website).text();
    });
    

    This should get the job done.

    EDIT: For any property:

    $.each(data, function(key, value) {
      $.each(value, function(_key, _value) {
         data[key][_key] = $('<div>'+_value+'</div>').text(); // <div></div> for those which are simply strings.
      });
    });