EN
JavaScript - what special characters should be escaped in <a href=""> attribute?
2 answers
8 points
I try to write own HTML escape function in JavaScript, but I am wondering if all special characters like <
, >
, &
, "
and '
should be escaped in <a href="">
attribute.
Anyone could confirm, my doubts?
2 answers
4 points
Possible solutions:
- You can find here information about universal HTML special characters escape function, so you can use it always with
<a href="">
attribute. - Alternatively, you can escape only selected characters depending on used HTML syntax:
'
character only for<a href='...'>
syntax ('
escaped to'
),"
character only for<a href="...">
syntax ("
escaped to"
or'
),
but more safety is to use Solution 1.
Note: do not forget to escape special characters in URI components using
encodeURIComponent()
function, what was described in this article.
0 commentsShow commentsAdd comment
3 points
If you would like to escape only '
and "
characters, it should be enough.
e.g.
xxxxxxxxxx
1
const SINGLE_QUOTATION_EXPRESSION = /'/g;
2
const DOUBLE_QUOTATION_EXPRESSION = /"/g;
3
4
const escapeAttribute = (value, character) => {
5
switch (character) {
6
case '\'': return value.replace(SINGLE_QUOTATION_EXPRESSION, '"');
7
case '"': return value.replace(DOUBLE_QUOTATION_EXPRESSION, '\'');
8
default: throw new Error('Incorrect escape character.');
9
}
10
};
11
12
13
// Usage example:
14
15
const value1 = escapeAttribute('https://example.com?name=\'John\'', '\''); // ' character is escaped
16
const value2 = escapeAttribute('https://example.com?name="John"', '"'); // " character is escaped
17
18
console.log(`<a href='${value1}'>`); // <a href='https://example.com?name="John"'>
19
console.log(`<a href="${value2}">`); // <a href="https://example.com?name='John'">
0 commentsAdd comment