Reputation: 56710
I'm creating a link to a page based on the name the user gave that page. However, the link is unclickable if the name is a zero-width space.
How can I stop users from giving pages unclickable names? I'd like to allow Unicode characters if possible.
The names are being entered into the database through a Django form, and the HTML link is being built in jQuery. Django complains if the name is a regular space, but accepts a zero-width space.
var linkText1 = 'foo', linkText2 = '\u200b';
$('#ex1')
.append($('<a>')
.text(linkText1)
.attr('href', 'javascript:alert("clicked.")'));
$('#ex2')
.append($('<a>')
.text(linkText2)
.attr('href', 'javascript:alert("clicked.")'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="ex1">Example 1 </p>
<p id="ex2">Example 2 </p>
Upvotes: 0
Views: 1288
Reputation: 56710
Inspired by Nawed's answer and devdob's comments, I decided to add a suffix when the link text didn't contain any letters or numbers. That will avoid corrupting any useful Unicode text, but it should always provide a usable link.
Unfortunately, it's not smart about Unicode. Chinese words, for example, will always get the link suffix.
Some options for improvement:
function addLink($p, linkText) {
if ( ! /\w/u.test(linkText)) {
linkText += ' [link]';
}
$p.append($('<a>')
.text(linkText)
.attr('href', 'javascript:alert("clicked.")'));
}
var linkText1 = 'foo', linkText2 = '\u200b', linkText3 = '网站';
addLink($('#ex1'), linkText1);
addLink($('#ex2'), linkText2);
addLink($('#ex3'), linkText3);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="ex1">Example 1 </p>
<p id="ex2">Example 2 </p>
<p id="ex3">Example 3 </p>
Upvotes: 0
Reputation: 4391
Detect and replace the zero-witdh space with null or empty space. Then when creating your link either skip that text (show no link if null) or show a default link text like "Click Here".
Here is some code to detect zero-width space and replace it with empty string:
linkText2 = linkText2.replace(/\u200B/g,'');
Here we set a default if given is empty:
linkText2 = (linkText2 == '') ? "Click Here" : linkText2;
Upvotes: 1