0

I have a JSON file that contains among it values for a specific property that is a string. In many of these strings, there are embedded <a href=".... </a> tags with different links. I want to go through the whole object and remove all of these tags, while leaving what is inside the tags.

1) Remove all <a .... >

2) Remove all </a>

Ikhlak S.
  • 8,578
  • 10
  • 57
  • 77
Miguel
  • 21
  • 1
  • 5
  • A "JSON file" is a file on the disk with a name such as `foo.json`. Do you mean you have a string in JSON format, or do you mean you have a JavaScript object? Also, what does "(1) Remove all (2) Remove all" mean? Also, is the problem to remove strings starting and ending with any identifiable characters, or HTML tags specifically? If the latter, is the HTML well-formed? Can you provide one or more examples of input and desired output? –  Nov 26 '16 at 04:00
  • Just deserialize the string and work with the resulting data structure to perform any desired transformations, then serialize back to JSON. – Mike Brant Nov 26 '16 at 04:03

2 Answers2

0

You could try regex or pass the content to an Element as HTML and get back as text. Please check the example below.

var data = {
  "content": "First part of the text. <b>This could be bold</b>. <span class=\"highlight\">Span with attribute.</span>"
};

var divElement = document.createElement('div');

divElement.innerHTML = data.content;

document.getElementById('text-content').innerHTML = divElement.innerText;
<div id="text-content"></div>
Darlesson
  • 5,742
  • 2
  • 21
  • 26
  • In case it matters, this will also translate strings such as `&` into an actual ampersand. –  Nov 26 '16 at 04:03
0

You could use a Regex to remove all <a ...> and </a> tags:

jsonObject.someString = jsonObject.someString.replace(/<[\/]{0,1}(a|A)[^><]*>/g,"");

If your object is large and would like to recursively remove all anchor tags within the object tree, take a look at this answer

JSFiddle

Community
  • 1
  • 1
Ikhlak S.
  • 8,578
  • 10
  • 57
  • 77