Ceejay
Ceejay

Reputation: 7267

How to compare encoded value with decoded value

Here i am trying to compare the values in option tag with values with JSON object.

I have 2 data forms

Format-1 - decoded

<li>please click <a target="_blank" href="https:app.answers/detail/a_id/140">here</a></li>

Format-2 - encoded

&lt;li&gt;please click &lt;a target=&quot;_blank&quot; href=&quot;https://app.answers/detail/a_id/140&quot;&gt;here&lt;/a&gt;&lt;/li&gt;

In the below code i am using unescape to decode the encoded value and using the decoded value to compare and making it checked, because the option value is in decoded format.

     for(j=0;j<multiValues.length;j++){
                var escapedVal = unescape(multiValues[j]);                               
                console.log(escapedVal); //this was suppose to show <li>please click <a target="_blank" href="https:app.answers/detail/a_id/140">here</a></li>   but its showing  &lt;li&gt;please click &lt;a target=&quot;_blank&quot; href=&quot;https://app.answers/detail/a_id/140&quot;&gt;here&lt;/a&gt;&lt;/li&gt;
$(v).find('option[value="'+escapedVal[j]+'"]').prop('selected',true).attr("selected","selected");
              }

When i log escapedVal it in console, its still displaying in the encoded format only. But i want to decode the format 2 and compare it with the format 1, because format 1 is already decoded. I am just comparing it in option value but i am not displaying it in page anywhere.

How can i do it?

Upvotes: 0

Views: 106

Answers (1)

gurvinder372
gurvinder372

Reputation: 68393

You need to decode this first and then compare

function decodeHTML( str )
{
  var div = document.createElement( "div" );
  div.innerHTML = str;
  return div.innerText;
}

Demo

function decodeHTML( str )
{
  var div = document.createElement( "div" );
  div.innerHTML = str;
  return div.innerText;
}
var value = '<li>please click <a target="_blank" href="https://app.answers/detail/a_id/140">here</a></li>';
var encodedValue = '&lt;li&gt;please click &lt;a target=&quot;_blank&quot; href=&quot;https://app.answers/detail/a_id/140&quot;&gt;here&lt;/a&gt;&lt;/li&gt;'
var recoveredValue = decodeHTML( encodedValue );

console.log( value == recoveredValue )

Upvotes: 1

Related Questions