Suleman Ahmad
Suleman Ahmad

Reputation: 2113

Append special characters in html tags

How to append special characters in html tags?

<html>
<head></head>
<body>
     <script>
        tool_tip_str = '!#$%^&&*()<>\'\"';
        var html = '<div title="' + tool_tip_str + '"> text is here </div>';
        document.write(html);
    </script>
</body>

This code is producing the result

<div "="" title="!#$%^&amp;&amp;*()&lt;&gt;'"> text is here </div>

But it should produce the

<div title="!#$%^&&*()<>\'\""> text is here </div>

why odd characters

"=""

are appending in result? Is there any way to show the single quotes or double quotes with out black slashes ?

Upvotes: 1

Views: 2454

Answers (2)

Albzi
Albzi

Reputation: 15609

JSFiddle

I got this result:

Image of source

Image of outcome

using this:

tool_tip_str = '!#$%^&&*()<>\'&quot;';

If you want to change all special characters to HTML entities, then you could write a function like:

function change(mystring)
{
  return mystring.replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;");
}

and then do:

tool_tip_str = change(tool_tip_str);

But obviously, you'd have to change everything in change() to get it exactly how you wanted.

Upvotes: 2

PeteAUK
PeteAUK

Reputation: 988

 <body>
      <script>
         tool_tip_str = '!#$%^&&*()<>\'\"';
         tool_tip_str = tool_tip_str.replace('"','&quot;');
         var html = '<div title="' + tool_tip_str + '"> text is here </div>';
         document.write(html);
     </script>
 </body>

Might need to convert the " into an html entity prior to outputting.

Upvotes: 0

Related Questions