How to Escape Double Quotes in a Title Attribute

How to escape double quotes in a title attribute

This variant -

<a title="Some "text"">Hover me</a>

Escaping the double quote that is in the attribute of an HTML tag

HTML doesn't use \ to escape characters, it uses entities.

"

How do I properly escape quotes inside HTML attributes?

" is the correct way, the third of your tests:

<option value=""asd">test</option>

You can see this working below, or on jsFiddle.

alert($("option")[0].value);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><select>  <option value=""asd">Test</option></select>

Escaping double double quotes in html attributes in Javascript

If it is HTML, you can use HTML entities to escape characters that might be interpreted otherwise. For example, " will be displayed as " in HTML attributes:

var content = '<input type="text" ng-model="test1" />';

Proof of concept: http://jsfiddle.net/teddyrised/5X5Ye/

Refer to W3C's HTML entities chart for more information: http://dev.w3.org/html5/html-author/charref

Escape single quotes in title

You can use double quote:

myTitle = "abc '' def";
document.write('<img title="' + myTitle + '" src="http://www.example.com/image.png" />');

or escape the quote:

myTitle = "abc '' def";
document.write("<img title='" + myTitle.replace(/'/g, ''') + "' src='http://www.example.com/image.png' />");

How to escape double quotes in HTML attribute value in Ruby?

To properly encode a double quote in an HTML attribute value, there are several ways:

  • You can use an unescaped " if the attribute value itself is delimited by '...' or vice-versa: (just like strings in Ruby)

    <meta property="og:name" content='some "thing"' />
  • If the attribute value is delimited by "...", you can use the double quote's numeric character reference ":

    <meta property="og:name" content='some "thing"' />
  • or its character entity reference ":

    <meta property="og:name" content="some "thing"" />

From within Ruby, you could call CGI.escapeHTML: (I'm using Ruby's %(...) percent string literal here for the meta tag string, so I don't have to escape all the ")

require 'cgi'

name = 'some "thing"'
meta = %(<meta property="og:name" content="#{CGI.escapeHTML(name)}" />)
#=> "<meta property=\"og:name\" content=\"some "thing"\" />"

puts meta

Or the tag helper if you're using Rails:

<%= tag(:meta, property: 'og:name', content: name) %>

Both of the above output:

<meta property="og:name" content="some "thing"" />

How can I escape double quotes in XML attributes values?

You can use "



Related Topics



Leave a reply



Submit