-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHTML_Special_Chars.js
More file actions
51 lines (40 loc) · 1.75 KB
/
HTML_Special_Chars.js
File metadata and controls
51 lines (40 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/* ----------------------------------------------------------------------------------------
Safen User Input Part I - htmlspecialchars
You are a(n) novice/average/experienced/professional/world-famous Web Developer
(choose one) who owns a(n) simple/clean/slick/beautiful/complicated/professional
/business website (choose one or more) which contains form fields so visitors can send
emails or leave a comment on your website with ease. However, with ease comes danger.
Every now and then, a hacker visits your website and attempts to compromise it through
the use of XSS (Cross Site Scripting). This is done by injecting script tags into the
website through form fields which may contain malicious code (e.g. a redirection to
a malicious website that steals personal information).
Mission
Your mission is to implement a function that converts the following potentially
harmful characters:
< --> <
> --> >
" --> "
& --> &
---------------------------------------------------------------------------------------- */
/*
String.prototype.replaceAll(): returns a new string with all matches of a pattern replaced
by a replacement.
*/
function htmlspecialchars(formData) {
return formData
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """);
}
/*
Alternative solution:
String.prototype.replace(): returns a new string with one, some, or all matches of a
pattern replaced by a replacement.
*/
function htmlspecialchars(formData) {
return formData.replace(
/[<>"&]/g,
(ch) => ({ "<": "<", ">": ">", '"': """, "&": "&" }[ch])
);
}