Reputation: 161
In my javascript code, I have a variable which have a string. String contains ' or quote in it. Example
var name= "hi's";
I am creating a link dynamically in a code. where it is written as a string i.e a variable content
will be used dynamically to create a link on html page.
content= '<a onclick="javascript:fun(\'' + name + '\');">'
Here it is giving problem that quote in variable name
completes the string in content. and hence rest portion of content is not recognised..
similar problem arises if var name = 'hi"s';
i.e. if double quote is present in it.
plz help
Upvotes: 3
Views: 4801
Reputation: 173602
This is how you would create an anchor properly and completely avoid the need to escape anything.
var name = "Hi's",
anchor = document.createElement('a');
// should have an href
// links will be displayed differently by some browsers without it
anchor.href = '#';
// using onclick for pragmatic reasons
anchor.onclick = function() {
fun(name);
return false;
}
anchor.innerHTML = 'hello world';
// later
mydiv.appendChild(anchor);
Btw, the onclick
attribute shouldn't start with "javascript:"
at all; that's already implied.
Update
If you're still interested in the inline version, variables need two steps of encoding:
The first is to serialize the variable properly; I would use JSON.stringify()
for that
The second is HTML escaping; the simplest form is simply to replace double quotes with their proper encoded values.
For example:
var content = '<a href="#" onclick="fun(' +
JSON.serialize(name).replace(/"/g, '"') + ');">hello</a>';
Upvotes: 3