-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring-escape.html
More file actions
867 lines (800 loc) · 50.9 KB
/
Copy pathstring-escape.html
File metadata and controls
867 lines (800 loc) · 50.9 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Free String Escape — JSON, HTML, URL Online | FreeDevTool</title>
<meta name="description" content="Escape and unescape strings for JSON, HTML, JavaScript, URL, CSV and SQL. Handle backslash escaping, special characters, newline tab quotes, HTML entities and URL encoding. Free, no signup.">
<meta name="robots" content="index, follow">
<meta name="author" content="Anees Ur Rehman">
<script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","datePublished":"2026-05-02","dateModified":"2026-05-19","inLanguage":"en-US","isPartOf":{"@type":"WebSite","name":"FreeDevTool","url":"https://freedevtool.org"}}</script>
<script type="application/ld+json">{"@context":"https://schema.org","@type":"Person","name":"Anees Ur Rehman","url":"https://freedevtool.org/about","jobTitle":"Full-stack developer","worksFor":{"@type":"Organization","name":"FreeDevTool","url":"https://freedevtool.org"}}</script>
<link rel="canonical" href="https://freedevtool.org/string-escape">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="preload" href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;700&family=DM+Sans:wght@300;400;500;600&display=swap" as="style">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;700&family=DM+Sans:wght@300;400;500;600&display=swap">
<link rel="preload" href="style.css?v=20260502-cards" as="style">
<link rel="stylesheet" href="style.css?v=20260502-cards">
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="/favicon.svg">
<meta property="og:image" content="https://freedevtool.org/og-image.svg">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="FreeDevTool — 50+ free, fast, privacy-first developer tools">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://freedevtool.org/og-image.svg">
<meta name="twitter:title" content="String Escape & Unescape — JSON, HTML, JS, URL, CSV, SQL">
<meta name="twitter:description" content="Escape and unescape strings for six formats with side-by-side input/output. Prevents XSS, SQL injection, JSON parse errors. Browser-only, no signup.">
<!-- Google Analytics 4 -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-3L0CMH3X36"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-3L0CMH3X36');
</script>
<meta property="og:title" content="String Escape & Unescape Tool Online — JSON, HTML, URL, JS, CSV, SQL">
<meta property="og:description" content="Escape and unescape strings for JSON, HTML, JavaScript, URL, CSV and SQL. Handle escape sequences, backslash escaping and special characters.">
<meta property="og:type" content="website">
<meta property="og:url" content="https://freedevtool.org/string-escape">
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "WebApplication",
"name": "String Escape & Unescape Tool Online",
"url": "https://freedevtool.org/string-escape",
"description": "Escape and unescape strings online for JSON, HTML, JavaScript, URL, CSV and SQL. Handle backslash escaping, special characters, escape sequences and more.",
"applicationCategory": "DeveloperApplication",
"operatingSystem": "Any",
"offers": { "@type": "Offer", "price": "0", "priceCurrency": "USD" }
}
</script>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "FAQPage",
"mainEntity": [
{
"@type": "Question",
"name": "What is string escaping and why is it needed?",
"acceptedAnswer": { "@type": "Answer", "text": "String escaping is the process of replacing special characters with escape sequences so they can be safely included in strings, code, or data formats. For example, a double quote inside a JSON string must be escaped as \\\" to avoid prematurely ending the string. Without escaping, special characters like quotes, backslashes, newlines, and tabs would break parsers, cause syntax errors, or create security vulnerabilities like SQL injection and XSS attacks." }
},
{
"@type": "Question",
"name": "How do I escape special characters in a JSON string?",
"acceptedAnswer": { "@type": "Answer", "text": "In JSON, you must escape the following characters inside strings: double quotes (\\\")), backslash (\\\\), newline (\\n), tab (\\t), carriage return (\\r), form feed (\\f), backspace (\\b), and any Unicode control character using \\uXXXX notation. JavaScript's JSON.stringify() handles this automatically. This tool performs the same escaping in your browser." }
},
{
"@type": "Question",
"name": "What is the difference between HTML encoding and URL encoding?",
"acceptedAnswer": { "@type": "Answer", "text": "HTML encoding converts characters to HTML entities (e.g., < becomes <) so they display as text in HTML documents instead of being interpreted as markup. URL encoding (percent-encoding) converts characters to %XX format (e.g., space becomes %20) so they can be safely included in URLs. They serve different purposes and are not interchangeable — HTML encoding is for rendering in web pages, URL encoding is for transmitting data in URLs." }
},
{
"@type": "Question",
"name": "How do I unescape a backslash-escaped string?",
"acceptedAnswer": { "@type": "Answer", "text": "To unescape a backslash-escaped string, replace each escape sequence with its corresponding character: \\n with a newline, \\t with a tab, \\\" with a double quote, \\\\ with a single backslash, and \\uXXXX with the corresponding Unicode character. This tool handles all standard escape sequences automatically. In JavaScript, JSON.parse() can unescape JSON-style escaped strings when wrapped in quotes." }
},
{
"@type": "Question",
"name": "Why is string escaping important for security?",
"acceptedAnswer": { "@type": "Answer", "text": "Proper string escaping prevents injection attacks — the most common class of web security vulnerabilities. Without escaping, attackers can inject malicious code: SQL injection exploits unescaped quotes in database queries, XSS (Cross-Site Scripting) exploits unescaped HTML/JavaScript in web pages, and command injection exploits unescaped shell characters. Always escape user input before inserting it into SQL queries, HTML output, URLs, or shell commands." }
},{"@type":"Question","name":"How do I escape a JSON string?","acceptedAnswer":{"@type":"Answer","text":"JSON requires escaping: backslash, double quote, forward slash (optional), newline, carriage return, tab, backspace, form feed, and Unicode escape sequences. Use the language built-in JSON serializer (JSON.stringify in JavaScript, json.dumps in Python) — never escape manually."}},{"@type":"Question","name":"What characters need to be escaped in JavaScript?","acceptedAnswer":{"@type":"Answer","text":"Inside a string literal: the same quote character used to delimit, plus backslash. Special whitespace also needs escaping (newline, tab, carriage return). Unicode characters can be escaped as Unicode escape sequences. Modern JavaScript prefers template literals to minimize escaping."}},{"@type":"Question","name":"Why do I need to escape strings in SQL queries?","acceptedAnswer":{"@type":"Answer","text":"To prevent SQL injection — a user-controlled string containing a quote and SQL keywords can break out of your intended query. Better: use parameterized queries (prepared statements) so the database engine handles escaping. Manual escape is error-prone."}}
]
}
</script>
<style>
.mode-tabs {
display: flex; gap: 6px; margin-bottom: 12px; flex-wrap: wrap;
}
.mode-tab {
font-family: var(--mono); font-size: 11px;
padding: 6px 14px; border: 1px solid var(--border);
border-radius: var(--radius); background: transparent;
color: var(--text2); cursor: pointer;
transition: border-color .2s, background .2s, color .2s;
}
.mode-tab:hover { border-color: var(--border2); background: var(--bg3); }
.mode-tab.active {
border-color: rgba(0,208,132,.3); background: var(--accent-dim);
color: var(--accent);
}
.dir-toggle {
display: inline-flex; align-items: center; gap: 8px;
margin-bottom: 12px;
}
.dir-toggle button {
font-family: var(--mono); font-size: 12px;
padding: 5px 16px; border: 1px solid var(--border);
border-radius: var(--radius); background: transparent;
color: var(--text2); cursor: pointer;
transition: border-color .2s, background .2s, color .2s;
}
.dir-toggle button:hover { border-color: var(--border2); background: var(--bg3); }
.dir-toggle button.active {
border-color: rgba(0,208,132,.3); background: var(--accent-dim);
color: var(--accent);
}
.dir-toggle .arrow { color: var(--text3); font-size: 14px; }
.char-count {
font-family: var(--mono); font-size: 11px;
color: var(--text3); text-align: right; margin-top: 4px;
}
.io-grid {
display: grid; grid-template-columns: 1fr 1fr; gap: 16px;
}
@media (max-width: 700px) {
.io-grid { grid-template-columns: 1fr; }
}
.io-col label { display: block; margin-bottom: 4px; }
.ref-table {
width: 100%; border-collapse: collapse; font-family: var(--mono); font-size: 12px;
background: var(--bg3); border: 1px solid var(--border); border-radius: var(--radius); overflow: hidden;
}
.ref-table th {
background: var(--bg4); padding: 8px 12px; text-align: left;
font-size: 10px; text-transform: uppercase; letter-spacing: .5px; color: var(--text3);
}
.ref-table td { padding: 6px 12px; border-top: 1px solid var(--border); }
.ref-table td:first-child { color: var(--accent); }
.ref-table td:nth-child(2) { color: var(--text2); }
</style>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "BreadcrumbList",
"itemListElement": [
{
"@type": "ListItem",
"position": 1,
"name": "Home",
"item": "https://freedevtool.org/"
},
{
"@type": "ListItem",
"position": 2,
"name": "All Tools",
"item": "https://freedevtool.org/all-tools"
},
{
"@type": "ListItem",
"position": 3,
"name": "String Escape & Unescape Tool",
"item": "https://freedevtool.org/string-escape"
}
]
}
</script>
<script src="/ga4-events.js" defer></script>
</head>
<body>
<nav>
<a class="nav-logo" href="/" aria-label="FreeDevTool home"><svg class="logo-mark" width="22" height="22" viewBox="0 0 24 24" aria-hidden="true" fill="none"><rect x="1" y="1" width="22" height="22" rx="6" fill="currentColor" opacity=".12"/><path d="M9.5 8.5L6 12l3.5 3.5M14.5 8.5L18 12l-3.5 3.5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>FreeDevTool</a>
<div class="nav-links">
<div class="nav-dropdown" id="tools-dropdown">
<a href="all-tools" onclick="event.preventDefault();this.parentElement.classList.toggle('open')" aria-haspopup="true">Tools <svg class="chev" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg></a>
<div class="nav-dropdown-menu">
<a href="encoding-tools">
<div class="dd-icon">b64</div>
<div class="dd-info"><div class="dd-name">Encoding & Conversion</div><div class="dd-count">11 tools · Base64, YAML, px→rem</div></div>
</a>
<a href="generation-tools">
<div class="dd-icon">{ }</div>
<div class="dd-info"><div class="dd-name">Generation & Formatting</div><div class="dd-count">16 tools · JSON, SQL, gradients</div></div>
</a>
<a href="security-tools">
<div class="dd-icon">#</div>
<div class="dd-info"><div class="dd-name">Security & Hashing</div><div class="dd-count">3 tools · JWT, MD5, SHA</div></div>
</a>
<a href="text-tools">
<div class="dd-icon">.*</div>
<div class="dd-info"><div class="dd-name">Code & Text Tools</div><div class="dd-count">9 tools · Regex, diff, tokens</div></div>
</a>
<a href="devops-tools">
<div class="dd-icon">JS</div>
<div class="dd-info"><div class="dd-name">Optimization & DevOps</div><div class="dd-count">7 tools · Minifiers, cURL, git</div></div>
</a>
<a href="network-tools">
<div class="dd-icon">IP</div>
<div class="dd-info"><div class="dd-name">Network & Time</div><div class="dd-count">4 tools · IP, DNS, timestamps</div></div>
</a>
<a href="seo-tools">
<div class="dd-icon">SEO</div>
<div class="dd-info"><div class="dd-name">SEO & Meta Tools</div><div class="dd-count">3 tools · OG, meta, slug</div></div>
</a>
<div class="nav-dropdown-divider"></div>
<a class="dd-all" href="all-tools">
<div class="dd-icon">All</div>
<div class="dd-info"><div class="dd-name">Browse all 50 tools</div><div class="dd-count">Searchable catalog & categories</div></div>
</a>
</div>
</div>
<a href="/guides">Guides</a>
<a href="about">About</a>
<a href="privacy">Privacy</a>
</div>
</nav>
<div id="copy-toast">Copied!</div>
<div class="wrapper">
<a class="tool-back" href="/" aria-label="Back to home">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 18l-6-6 6-6"/></svg>
Back
</a>
<div class="tool-header">
<div class="tool-badge">Text Tool</div>
<h1>String Escape & Unescape Tool</h1>
<p class="tool-description">
Escape and unescape strings online for <strong>JSON</strong>, <strong>HTML</strong>, <strong>JavaScript</strong>, <strong>URL</strong>, <strong>CSV</strong> and <strong>SQL</strong>. This free tool handles backslash escaping, escape sequences for newline, tab and quotes, HTML entities, URL percent-encoding, and SQL injection prevention. Paste any string to instantly see the escaped or unescaped result. Supports Unicode <code>\uXXXX</code> notation, special characters, and all common escape formats. All processing happens client-side in your browser — nothing is uploaded to a server.
</p>
<div class="last-updated">Last updated: May 2026 · Written by <a href="/about">Anees Ur Rehman</a>, full-stack developer</div>
</div>
<div class="tool-card">
<div class="tool-card-header">
<div class="dot dot-red"></div>
<div class="dot dot-yellow"></div>
<div class="dot dot-green"></div>
<span class="tool-card-title">string-escape.tool</span>
</div>
<div class="tool-body">
<!-- Mode selector -->
<label>Escape Mode</label>
<div class="mode-tabs" id="mode-tabs">
<button class="mode-tab active" data-mode="json" onclick="setMode('json',this)">JSON</button>
<button class="mode-tab" data-mode="html" onclick="setMode('html',this)">HTML</button>
<button class="mode-tab" data-mode="js" onclick="setMode('js',this)">JavaScript</button>
<button class="mode-tab" data-mode="url" onclick="setMode('url',this)">URL</button>
<button class="mode-tab" data-mode="csv" onclick="setMode('csv',this)">CSV</button>
<button class="mode-tab" data-mode="sql" onclick="setMode('sql',this)">SQL</button>
</div>
<!-- Direction toggle -->
<div class="dir-toggle">
<button id="dir-esc" class="active" onclick="setDir('escape')">Escape</button>
<span class="arrow">↔</span>
<button id="dir-unesc" onclick="setDir('unescape')">Unescape</button>
</div>
<!-- Input / Output -->
<div class="io-grid">
<div class="io-col">
<label id="input-label">Input</label>
<textarea id="input" rows="10" placeholder="Paste your string here..." oninput="convert()"></textarea>
<div class="char-count" id="input-count">0 characters</div>
</div>
<div class="io-col">
<div class="output-label">
<label id="output-label" style="margin:0">Output</label>
<button class="btn btn-ghost" onclick="copyOutput()">Copy</button>
</div>
<textarea id="output" rows="10" readonly placeholder="Result will appear here..."></textarea>
<div class="char-count" id="output-count">0 characters</div>
</div>
</div>
<div class="divider"></div>
<!-- Quick Reference Table -->
<label>Common Escape Sequences Reference</label>
<table class="ref-table">
<tr><th>Sequence</th><th>Character</th><th>Description</th></tr>
<tr><td>\\</td><td>\</td><td>Backslash</td></tr>
<tr><td>\"</td><td>"</td><td>Double quote</td></tr>
<tr><td>\'</td><td>'</td><td>Single quote</td></tr>
<tr><td>\n</td><td>↵</td><td>Newline (line feed)</td></tr>
<tr><td>\r</td><td></td><td>Carriage return</td></tr>
<tr><td>\t</td><td>→</td><td>Horizontal tab</td></tr>
<tr><td>\b</td><td></td><td>Backspace</td></tr>
<tr><td>\f</td><td></td><td>Form feed</td></tr>
<tr><td>\0</td><td></td><td>Null character</td></tr>
<tr><td>\uXXXX</td><td></td><td>Unicode code point (hex)</td></tr>
</table>
</div>
</div>
<p class="aeo-lead" style="font-size:16px;line-height:1.7;color:var(--text);max-width:760px;margin:24px auto 18px;padding:0 4px">
<strong>String escaping</strong> adds backslash sequences (<code>
</code>, <code>"</code>, <code>\</code>) so a string can be embedded inside another context (code, JSON, HTML, SQL, regex, shell) without breaking the parent syntax. Each context has different escape rules. This <strong>free string escape tool</strong> handles six contexts — JavaScript, JSON, HTML attribute, SQL string, regex pattern, shell argument — in both directions.
</p>
<section id="examples" style="max-width:760px;margin:24px auto 32px">
<h2 style="font-size:18px;margin-bottom:14px">Examples</h2>
<div style="background:var(--bg3);border:1px solid var(--border);border-radius:var(--radius);padding:16px;margin-bottom:12px">
<strong style="display:block;color:var(--accent);font-family:var(--mono);font-size:11px;text-transform:uppercase;letter-spacing:1px;margin-bottom:6px">JSON string escape§§Input: She said "hi" and waved§§JSON: "She said \\"hi\\" and waved"§§Backslash before any embedded quote.</strong>
</div>
<div style="background:var(--bg3);border:1px solid var(--border);border-radius:var(--radius);padding:16px;margin-bottom:12px">
<strong style="display:block;color:var(--accent);font-family:var(--mono);font-size:11px;text-transform:uppercase;letter-spacing:1px;margin-bottom:6px">JavaScript template literal§§Input: line one${"\\n"}line two§§Escaped: "line one\\nline two"§§Or use a template literal with literal newlines.</strong>
</div>
<div style="background:var(--bg3);border:1px solid var(--border);border-radius:var(--radius);padding:16px;margin-bottom:12px">
<strong style="display:block;color:var(--accent);font-family:var(--mono);font-size:11px;text-transform:uppercase;letter-spacing:1px;margin-bottom:6px">Shell single-quote vs double-quote§§Single: '$HOME' is literal "$HOME"§§Double: "$HOME" expands to /home/user§§Wrap unknown user input in single quotes to prevent variable expansion attacks.</strong>
</div>
</section>
<aside class="founder-note" style="max-width:760px;margin:24px auto 32px;padding:20px 24px;background:rgba(0,208,132,0.05);border-left:3px solid var(--accent);border-radius:6px;font-size:14px;line-height:1.7;color:var(--text2)"><div style="font-family:var(--mono);font-size:11px;color:var(--accent);letter-spacing:1.5px;text-transform:uppercase;margin-bottom:10px;font-weight:600">💡 Why I built this</div><p style="margin:0 0 12px">I built this after spending too long pasting a regex from a JavaScript file into a JSON config and watching every backslash silently vanish. Different contexts need different escape rules — JS string, JSON string, HTML attribute, SQL string, regex pattern, shell argument — and getting them wrong creates ‘works locally, breaks in production’ bugs. This tool handles all six contexts, in both directions.</p><p style="margin:0;font-size:13px;color:var(--text3)">— <a href="/about" style="color:var(--accent);text-decoration:none">Anees Ur Rehman</a>, full-stack developer</p></aside>
<section class="article-section">
<h2>The complete guide to string escaping — JSON, HTML, JavaScript, URL, CSV, and SQL</h2>
<p>Every string-related security incident I have read in the past decade — Equifax, MOVEit, Log4Shell, every weekend's fresh round of XSS reports — traces back to a string that crossed a context boundary without being re-escaped for the new context. Escaping is not boilerplate; it is the rule that keeps user data inside its data envelope and prevents it from being interpreted as code. This guide covers each escaping context the tool supports — what the escape sequences are, what the parser is actually defending against, and the language-level functions you should reach for instead of writing your own.</p>
<h3>Context is everything — the same string needs different escaping in different places</h3>
<p>The single biggest concept to internalise is <strong>context-specific escaping</strong>. A string flowing from a database into an HTML page should be HTML-escaped at the moment it is written into HTML. The same string flowing into a JavaScript string literal needs JS-string escaping. The same string going into a URL parameter needs percent-encoding. None of these escapings substitute for each other:</p>
<table class="ref-table">
<thead><tr><th>Where the string lands</th><th>Escape with</th><th>What it prevents</th></tr></thead>
<tbody>
<tr><td>HTML element body (<code><p>…</p></code>)</td><td>HTML entity escape <code>& < ></code></td><td>HTML/XSS injection</td></tr>
<tr><td>HTML attribute value</td><td>HTML entity escape + always quote attribute</td><td>Attribute breakout, event handlers</td></tr>
<tr><td>JavaScript string literal</td><td>JS escape (<code>\\ \" \n \uXXXX</code>)</td><td>String breakout, code injection</td></tr>
<tr><td>URL query parameter</td><td>percent-encoding (<code>encodeURIComponent</code>)</td><td>Param injection, broken parsers</td></tr>
<tr><td>JSON value</td><td>JSON escape (<code>JSON.stringify</code>)</td><td>JSON parse errors, injection</td></tr>
<tr><td>CSV cell</td><td>Wrap in <code>"…"</code>, double internal <code>""</code></td><td>Cell breakout, CSV injection</td></tr>
<tr><td>SQL value</td><td><strong>Don't escape — use a parameterised query</strong></td><td>SQL injection</td></tr>
<tr><td>Shell command</td><td><strong>Don't escape — use exec with arg array</strong></td><td>Command injection</td></tr>
</tbody>
</table>
<p>The two "don't escape" rows in that table are deliberate — they are the two places where ad-hoc escaping is the wrong tool. We will come back to them.</p>
<h3>JSON escaping — what RFC 8259 actually requires</h3>
<p>RFC 8259 (the current JSON spec) requires escaping just six characters inside string values: <code>"</code>, <code>\</code>, and the U+0000–U+001F control range. Everything else is allowed verbatim, including non-ASCII. Most JSON encoders also escape <code>/</code> defensively (so the string <code></script></code> doesn't break out of an inline JSON-in-HTML block), and many escape all non-ASCII to <code>\uXXXX</code> for transport safety:</p>
<ul>
<li><code>\"</code> — double quote</li>
<li><code>\\</code> — backslash</li>
<li><code>\/</code> — forward slash (optional, but recommended for <code></script></code> safety)</li>
<li><code>\b \f \n \r \t</code> — control whitespace</li>
<li><code>\uXXXX</code> — any other control character or non-ASCII</li>
</ul>
<p>The simple rule in JavaScript: if you can use <code>JSON.stringify(value)</code>, do that. It is correct, fast, and tested by every browser vendor. Hand-rolling JSON escaping is how you get parse errors with surrogate pairs and U+2028 (line separator, which used to break JSONP).</p>
<h3>HTML escaping — the OWASP rule of five</h3>
<p>OWASP's HTML escaping recommendation is to encode five characters in element bodies:</p>
<table class="ref-table">
<thead><tr><th>Char</th><th>Entity</th><th>Why</th></tr></thead>
<tbody>
<tr><td><code>&</code></td><td><code>&amp;</code></td><td>Must come first or it'll re-escape your other entities</td></tr>
<tr><td><code><</code></td><td><code>&lt;</code></td><td>Prevents tag injection</td></tr>
<tr><td><code>></code></td><td><code>&gt;</code></td><td>Defensive; some legacy parsers care</td></tr>
<tr><td><code>"</code></td><td><code>&quot;</code></td><td>Prevents attribute-value breakout</td></tr>
<tr><td><code>'</code></td><td><code>&#39;</code> or <code>&#x27;</code></td><td>Same — <code>&apos;</code> isn't valid in HTML4</td></tr>
</tbody>
</table>
<p>This baseline covers element-body and double-quoted-attribute contexts. <strong>It does not cover</strong> JavaScript-event attributes (<code>onclick</code>), <code>style</code> attributes, or <code>href</code>/<code>src</code> URLs — those need additional context-specific encoding. The rule of thumb: never put untrusted data inside <code><script></code>, <code><style></code>, or unquoted attributes, ever.</p>
<h3>URL encoding — encodeURIComponent vs encodeURI</h3>
<p>This trips up everyone at least once. JavaScript ships two URL-encoding functions and they do different things:</p>
<ul>
<li><strong><code>encodeURI(url)</code></strong> — encodes a full URL but leaves <code>: / ? & = #</code> alone because they are URL syntax characters. Use this on a complete URL you want to make safe for transmission, never on user data.</li>
<li><strong><code>encodeURIComponent(value)</code></strong> — encodes <em>everything</em> except <code>A-Z a-z 0-9 - _ . ! ~ * ' ( )</code>. Use this on every individual query parameter value or path segment.</li>
</ul>
<p>If you ever find yourself reaching for <code>escape()</code> — stop. <code>escape()</code> is deprecated, produces non-standard output for non-ASCII, and is the wrong answer for everything in 2026.</p>
<h3>CSV escaping — the RFC 4180 rules</h3>
<p>CSV escaping is delightfully short:</p>
<ol>
<li>If the field contains <code>,</code>, <code>"</code>, <code>\r</code>, or <code>\n</code>, wrap the entire field in double quotes.</li>
<li>Inside that wrapping, double up any embedded <code>"</code> (so a single quote becomes <code>""</code>).</li>
</ol>
<p>That is it. There is no standard backslash escaping in CSV; <code>\n</code> as two characters is treated literally. The other major risk — <strong>CSV injection</strong> — is when a field starts with <code>=</code>, <code>+</code>, <code>-</code>, or <code>@</code> and Excel evaluates it as a formula on import. The OWASP fix: prefix any such cell with a single quote (<code>'</code>) before saving. The picker handles RFC 4180 escaping; CSV-injection prefixing is a downstream sanitization step.</p>
<h3>SQL escaping — why you should not be doing it</h3>
<p>SQL "escaping" is the most dangerous category in this list. The historical pattern was to double-up single quotes (<code>O'Brien</code> → <code>O''Brien</code>) and string-concatenate the result into a query. <strong>Do not do this.</strong> Quoting alone does not defend against:</p>
<ul>
<li>Numeric injection — when the field has no quotes around it, escaping quotes does nothing.</li>
<li>LIKE pattern injection — quoting <code>%</code> and <code>_</code> requires a separate ESCAPE clause.</li>
<li>Identifier injection — table/column names can't be parameterised in most drivers.</li>
<li>Encoding-collision attacks — the classic <code>0xBF 0x27</code> bypass on misconfigured MySQL connections.</li>
</ul>
<p>The correct answer is parameterised queries / prepared statements, where the database driver sends the SQL template and the values separately and the database engine never confuses them. Every modern driver supports this:</p>
<div class="lang-block"><strong>Node.js (pg):</strong><pre><code>await client.query('SELECT * FROM users WHERE email = $1', [userEmail]);</code></pre></div>
<div class="lang-block"><strong>Python (psycopg / sqlalchemy):</strong><pre><code>cur.execute('SELECT * FROM users WHERE email = %s', (user_email,))</code></pre></div>
<div class="lang-block"><strong>Java (JDBC):</strong><pre><code>PreparedStatement ps = conn.prepareStatement(
"SELECT * FROM users WHERE email = ?");
ps.setString(1, userEmail);</code></pre></div>
<p>The SQL escape mode in this tool exists for emergency cases (one-off scripts, escaping a literal for a SQL editor pasted by hand). It should never be the layer that protects production code from injection.</p>
<h3>JavaScript string escaping — the surprises</h3>
<p>JavaScript string literals support a long list of escapes, and a few have non-obvious behavior:</p>
<ul>
<li><code>\xNN</code> — two-digit hex, U+0000 to U+00FF.</li>
<li><code>\uNNNN</code> — four-digit hex, U+0000 to U+FFFF (a single UTF-16 code unit, which means surrogates land here).</li>
<li><code>\u{NNNNNN}</code> — variable-length, full Unicode 0x0 to 0x10FFFF (ES2015+). Use this for emoji and astral characters; it produces a correct surrogate pair.</li>
<li><code>\0</code> — null, but only when not followed by a digit. <code>\01</code> is an octal escape and a syntax error in strict mode.</li>
<li><code>\v</code> — vertical tab (U+000B), almost never used.</li>
<li>Line continuation — a backslash at end of line continues the string. Allowed but discouraged.</li>
</ul>
<p>JavaScript also has two characters that can break inline JSON-in-script blocks: U+2028 (line separator) and U+2029 (paragraph separator). They are valid in JSON but were illegal in JS string literals until 2019. Older code that writes <code><script>var data = ${JSON.stringify(x)};</script></code> needs to escape these to <code>
</code>/<code>
</code> for safety.</p>
<h3>Common escaping mistakes that turn into vulnerabilities</h3>
<ul>
<li><strong>Double-encoding.</strong> Encoding a string twice ("just to be safe") makes <code>&amp;amp;</code> appear in your UI. Encode once, at the boundary.</li>
<li><strong>Escaping at the wrong layer.</strong> Sanitising user input on its way <em>in</em> to the database means every other consumer needs to know that. Escape on the way <em>out</em>, in the context of the destination.</li>
<li><strong>Building HTML by string concatenation.</strong> Use a templating engine that escapes by default (Handlebars <code>{{x}}</code>, JSX <code>{x}</code>, Jinja2 autoescape on). Mistakes are caught at the language level.</li>
<li><strong>Escaping URL-encoded data again.</strong> If you call <code>encodeURIComponent</code> on something that's already encoded you get <code>%2520</code> instead of <code>%20</code>.</li>
<li><strong>Using <code>innerHTML</code> with sanitised input.</strong> Even sanitised HTML can carry mutation-XSS payloads. Prefer <code>textContent</code> for plain text; use <code>setAttribute</code> for attributes; use a vetted HTML sanitiser (DOMPurify) when you really need to render rich HTML.</li>
<li><strong>Trusting the regex you wrote in 2018.</strong> Browsers, attack techniques, and parser quirks all evolve. Use the platform escape function (<code>encodeURIComponent</code>, <code>JSON.stringify</code>, <code>DOMPurify.sanitize</code>) instead.</li>
<li><strong>Forgetting to escape the same string twice across formats.</strong> A string going into a JSON-in-HTML attribute needs both JSON encoding <em>and</em> HTML attribute encoding. Order: JSON first, then HTML escape the result.</li>
</ul>
<aside class="article-aside">
<strong>Authoritative references:</strong>
<ul>
<li><a href="https://datatracker.ietf.org/doc/html/rfc8259" rel="noopener" target="_blank">RFC 8259 — JSON data interchange format</a></li>
<li><a href="https://datatracker.ietf.org/doc/html/rfc4180" rel="noopener" target="_blank">RFC 4180 — CSV format</a></li>
<li><a href="https://datatracker.ietf.org/doc/html/rfc3986" rel="noopener" target="_blank">RFC 3986 — URI generic syntax (percent-encoding)</a></li>
<li><a href="https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html" rel="noopener" target="_blank">OWASP — XSS Prevention Cheat Sheet (context-specific encoding)</a></li>
<li><a href="https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html" rel="noopener" target="_blank">OWASP — SQL Injection Prevention Cheat Sheet</a></li>
</ul>
</aside>
</section>
<!-- FAQ -->
<section class="faq-section">
<h2>Frequently Asked Questions</h2>
<div class="faq-item open">
<div class="faq-q" onclick="toggleFaq(this)">
What is string escaping and why is it needed?
<svg class="chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>
</div>
<div class="faq-a">
String escaping is the process of replacing special characters with <strong>escape sequences</strong> so they can be safely included in strings, code, or data formats. For example, a double quote inside a JSON string must be written as <code>\"</code> to avoid prematurely ending the string. Without proper escaping, special characters like quotes, backslashes, newlines, and tabs would break parsers, cause syntax errors, or create security vulnerabilities such as SQL injection and XSS attacks.
</div>
</div>
<div class="faq-item">
<div class="faq-q" onclick="toggleFaq(this)">
How do I escape special characters in a JSON string?
<svg class="chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>
</div>
<div class="faq-a">
In JSON, the following characters must be escaped inside strings: double quotes (<code>\"</code>), backslash (<code>\\</code>), newline (<code>\n</code>), tab (<code>\t</code>), carriage return (<code>\r</code>), form feed (<code>\f</code>), backspace (<code>\b</code>), and any Unicode control character using <code>\uXXXX</code> notation. JavaScript's <code>JSON.stringify()</code> handles this automatically. This tool performs the same escaping entirely in your browser.
</div>
</div>
<div class="faq-item">
<div class="faq-q" onclick="toggleFaq(this)">
What is the difference between HTML encoding and URL encoding?
<svg class="chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>
</div>
<div class="faq-a">
<strong>HTML encoding</strong> converts characters to HTML entities (e.g., <code><</code> becomes <code>&lt;</code>) so they display as visible text in web pages instead of being interpreted as markup. <strong>URL encoding</strong> (percent-encoding) converts characters to <code>%XX</code> format (e.g., a space becomes <code>%20</code>) so they can be safely included in URLs. They serve different purposes and are not interchangeable — HTML encoding prevents markup injection in pages, while URL encoding ensures characters are transmitted correctly in URLs.
</div>
</div>
<div class="faq-item">
<div class="faq-q" onclick="toggleFaq(this)">
How do I unescape a backslash-escaped string?
<svg class="chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>
</div>
<div class="faq-a">
To unescape a backslash-escaped string, replace each escape sequence with its corresponding character: <code>\n</code> with a newline, <code>\t</code> with a tab, <code>\"</code> with a double quote, <code>\\</code> with a single backslash, and <code>\uXXXX</code> with the corresponding Unicode character. This tool handles all standard escape sequences automatically. In JavaScript, <code>JSON.parse()</code> can unescape JSON-style escaped strings when the input is wrapped in double quotes.
</div>
</div>
<div class="faq-item">
<div class="faq-q" onclick="toggleFaq(this)">
Why is string escaping important for security?
<svg class="chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>
</div>
<div class="faq-a">
Proper string escaping prevents <strong>injection attacks</strong> — the most common class of web security vulnerabilities. Without escaping, attackers can inject malicious code: <strong>SQL injection</strong> exploits unescaped quotes in database queries, <strong>XSS (Cross-Site Scripting)</strong> exploits unescaped HTML and JavaScript in web pages, and <strong>command injection</strong> exploits unescaped shell characters. Always escape user input before inserting it into SQL queries, HTML output, URLs, or shell commands.
</div>
</div>
</section>
<!-- Related Tools -->
<section class="related-section">
<h2>Related Tools</h2>
<div class="related-grid">
<a class="related-card" href="json-formatter">
<div class="related-icon">{ }</div>
<div class="related-card-info">
<div class="related-card-name">JSON Formatter</div>
<div class="related-card-desc">Pretty print and validate JSON</div>
</div>
</a>
<a class="related-card" href="url-encoder">
<div class="related-icon">%</div>
<div class="related-card-info">
<div class="related-card-name">URL Encoder</div>
<div class="related-card-desc">Percent-encode and decode URLs</div>
</div>
</a>
<a class="related-card" href="html-entity">
<div class="related-icon">&</div>
<div class="related-card-info">
<div class="related-card-name">HTML Entity Encoder</div>
<div class="related-card-desc">Encode special characters to HTML entities</div>
</div>
</a>
</div>
</section>
<section class="all-tools-section" aria-label="Browse all FreeDevTool developer tools">
<h2>Browse all 50 free developer tools</h2>
<p class="atc-sub">All tools run in your browser, no signup required, nothing sent to a server.</p>
<div class="all-tools-grid">
<div class="atc-cat">
<div class="atc-cat-head">
<div class="atc-cat-icon">b64</div>
<div class="atc-cat-title"><h3>Encoding & Conversion</h3><span class="atc-cat-count">11 tools</span></div>
</div>
<ul class="atc-list">
<li><a href="/base64-encoder">Base64 Encoder / Decoder</a></li>
<li><a href="/base64-image">Image to Base64</a></li>
<li><a href="/byte-converter">Byte Converter (KB / MB / GB)</a></li>
<li><a href="/case-converter">Case Converter</a></li>
<li><a href="/hex-to-rgb">Hex to RGB / HSL</a></li>
<li><a href="/html-entity">HTML Entity Encoder</a></li>
<li><a href="/json-to-csv">JSON to CSV Converter</a></li>
<li><a href="/px-to-rem">PX to REM Converter</a></li>
<li><a href="/string-escape">String Escape / Unescape</a></li>
<li><a href="/url-encoder">URL Encoder / Decoder</a></li>
<li><a href="/yaml-to-json">YAML to JSON Converter</a></li>
</ul>
</div>
<div class="atc-cat">
<div class="atc-cat-head">
<div class="atc-cat-icon">{ }</div>
<div class="atc-cat-title"><h3>Formatting & Generators</h3><span class="atc-cat-count">13 tools</span></div>
</div>
<ul class="atc-list">
<li><a href="/color-name">Color Name from Hex</a></li>
<li><a href="/color-picker">Color Palette Picker</a></li>
<li><a href="/css-box-shadow">CSS Box Shadow</a></li>
<li><a href="/css-gradient">CSS Gradient Generator</a></li>
<li><a href="/json-formatter">JSON Formatter / Validator</a></li>
<li><a href="/lorem-ipsum">Lorem Ipsum Generator</a></li>
<li><a href="/markdown-preview">Markdown Preview</a></li>
<li><a href="/password-generator">Password Generator</a></li>
<li><a href="/qr-generator">QR Code Generator</a></li>
<li><a href="/sql-formatter">SQL Formatter</a></li>
<li><a href="/uuid-generator">UUID Generator</a></li>
<li><a href="/word-to-markdown">Word to Markdown</a></li>
<li><a href="/xml-formatter">XML Formatter</a></li>
</ul>
</div>
<div class="atc-cat">
<div class="atc-cat-head">
<div class="atc-cat-icon">JS</div>
<div class="atc-cat-title"><h3>Minifiers & DevOps</h3><span class="atc-cat-count">6 tools</span></div>
</div>
<ul class="atc-list">
<li><a href="/chmod-calculator">chmod Calculator</a></li>
<li><a href="/cron-parser">Cron Expression Parser</a></li>
<li><a href="/css-minifier">CSS Minifier</a></li>
<li><a href="/html-minifier">HTML Minifier</a></li>
<li><a href="/js-minifier">JavaScript Minifier</a></li>
<li><a href="/http-status">HTTP Status Codes</a></li>
</ul>
</div>
<div class="atc-cat">
<div class="atc-cat-head">
<div class="atc-cat-icon">#</div>
<div class="atc-cat-title"><h3>Security & Hashing</h3><span class="atc-cat-count">3 tools</span></div>
</div>
<ul class="atc-list">
<li><a href="/hash-generator">Hash Generator (MD5, SHA)</a></li>
<li><a href="/jwt-decoder">JWT Decoder</a></li>
<li><a href="/jwt-generator">JWT Generator</a></li>
</ul>
</div>
<div class="atc-cat">
<div class="atc-cat-head">
<div class="atc-cat-icon">.*</div>
<div class="atc-cat-title"><h3>Code & Text</h3><span class="atc-cat-count">8 tools</span></div>
</div>
<ul class="atc-list">
<li><a href="/ai-token-counter">AI Token Counter</a></li>
<li><a href="/char-counter">Character & Word Counter</a></li>
<li><a href="/git-cheatsheet">Git Commands Cheatsheet</a></li>
<li><a href="/number-base">Number Base Converter</a></li>
<li><a href="/regex-explainer">Regex Explainer</a></li>
<li><a href="/regex-tester">Regex Tester</a></li>
<li><a href="/text-diff">Text Diff Checker</a></li>
<li><a href="/wcag-contrast">WCAG Contrast Checker</a></li>
</ul>
</div>
<div class="atc-cat">
<div class="atc-cat-head">
<div class="atc-cat-icon">IP</div>
<div class="atc-cat-title"><h3>Network & APIs</h3><span class="atc-cat-count">3 tools</span></div>
</div>
<ul class="atc-list">
<li><a href="/dns-lookup">DNS Lookup</a></li>
<li><a href="/http-request-builder">HTTP Request Builder</a></li>
<li><a href="/ip-lookup">IP Address Lookup</a></li>
</ul>
</div>
<div class="atc-cat">
<div class="atc-cat-head">
<div class="atc-cat-icon">⏱</div>
<div class="atc-cat-title"><h3>Time & Dates</h3><span class="atc-cat-count">3 tools</span></div>
</div>
<ul class="atc-list">
<li><a href="/relative-time">Relative Time Calculator</a></li>
<li><a href="/timestamp-diff">Timestamp Diff</a></li>
<li><a href="/unix-timestamp-converter">Unix Timestamp Converter</a></li>
</ul>
</div>
<div class="atc-cat">
<div class="atc-cat-head">
<div class="atc-cat-icon">SEO</div>
<div class="atc-cat-title"><h3>SEO & Meta</h3><span class="atc-cat-count">3 tools</span></div>
</div>
<ul class="atc-list">
<li><a href="/meta-tag-generator">Meta Tag Generator</a></li>
<li><a href="/og-preview">Open Graph Preview</a></li>
<li><a href="/slug-generator">URL Slug Generator</a></li>
</ul>
</div>
</div>
</section>
</div>
<footer>
<div>© 2026 FreeDevTool — String Escape Tool</div>
<div class="footer-links">
<a href="/all-tools">All Tools</a>
<a href="/about">About</a>
<a href="/privacy">Privacy Policy</a>
<a href="/terms">Terms of Use</a>
</div>
</footer>
<script>
let currentMode = 'json';
let currentDir = 'escape';
function setMode(mode, btn) {
currentMode = mode;
document.querySelectorAll('.mode-tab').forEach(t => t.classList.remove('active'));
btn.classList.add('active');
convert();
}
function setDir(dir) {
currentDir = dir;
document.getElementById('dir-esc').classList.toggle('active', dir === 'escape');
document.getElementById('dir-unesc').classList.toggle('active', dir === 'unescape');
document.getElementById('input-label').textContent = dir === 'escape' ? 'Input' : 'Escaped Input';
document.getElementById('output-label').textContent = dir === 'escape' ? 'Escaped Output' : 'Unescaped Output';
convert();
}
function convert() {
const input = document.getElementById('input').value;
const out = document.getElementById('output');
document.getElementById('input-count').textContent = input.length + ' characters';
if (!input) {
out.value = '';
document.getElementById('output-count').textContent = '0 characters';
return;
}
let result = '';
try {
if (currentDir === 'escape') {
result = escapeStr(input, currentMode);
} else {
result = unescapeStr(input, currentMode);
}
out.style.color = 'var(--text)';
} catch (e) {
result = 'Error: ' + e.message;
out.style.color = 'var(--red, #f55)';
}
out.value = result;
document.getElementById('output-count').textContent = result.length + ' characters';
}
/* ---- Escape functions ---- */
function escapeStr(str, mode) {
switch (mode) {
case 'json': return escapeJSON(str);
case 'html': return escapeHTML(str);
case 'js': return escapeJS(str);
case 'url': return encodeURIComponent(str);
case 'csv': return escapeCSV(str);
case 'sql': return escapeSQL(str);
default: return str;
}
}
function unescapeStr(str, mode) {
switch (mode) {
case 'json': return unescapeJSON(str);
case 'html': return unescapeHTML(str);
case 'js': return unescapeJS(str);
case 'url': return decodeURIComponent(str);
case 'csv': return unescapeCSV(str);
case 'sql': return unescapeSQL(str);
default: return str;
}
}
/* JSON */
function escapeJSON(str) {
// Use JSON.stringify then strip outer quotes
return JSON.stringify(str).slice(1, -1);
}
function unescapeJSON(str) {
// Wrap in quotes and parse
return JSON.parse('"' + str + '"');
}
/* HTML */
function escapeHTML(str) {
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function unescapeHTML(str) {
const el = document.createElement('textarea');
el.innerHTML = str;
return el.value;
}
/* JavaScript */
function escapeJS(str) {
return str
.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'")
.replace(/"/g, '\\"')
.replace(/`/g, '\\`')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\t/g, '\\t')
.replace(/\f/g, '\\f')
.replace(/\b/g, '\\b')
.replace(/\0/g, '\\0')
.replace(/[\x00-\x1F\x7F]/g, function(c) {
return '\\x' + c.charCodeAt(0).toString(16).padStart(2, '0');
})
.replace(/[\u0080-\uFFFF]/g, function(c) {
return '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0');
});
}
function unescapeJS(str) {
// Handle standard JS escape sequences
let result = '';
let i = 0;
while (i < str.length) {
if (str[i] === '\\' && i + 1 < str.length) {
const next = str[i + 1];
switch (next) {
case 'n': result += '\n'; i += 2; break;
case 'r': result += '\r'; i += 2; break;
case 't': result += '\t'; i += 2; break;
case 'f': result += '\f'; i += 2; break;
case 'b': result += '\b'; i += 2; break;
case '0': result += '\0'; i += 2; break;
case '\\': result += '\\'; i += 2; break;
case "'": result += "'"; i += 2; break;
case '"': result += '"'; i += 2; break;
case '`': result += '`'; i += 2; break;
case 'x':
if (i + 3 < str.length) {
result += String.fromCharCode(parseInt(str.substring(i + 2, i + 4), 16));
i += 4;
} else { result += str[i]; i++; }
break;
case 'u':
if (str[i + 2] === '{') {
const end = str.indexOf('}', i + 3);
if (end !== -1) {
result += String.fromCodePoint(parseInt(str.substring(i + 3, end), 16));
i = end + 1;
} else { result += str[i]; i++; }
} else if (i + 5 < str.length) {
result += String.fromCharCode(parseInt(str.substring(i + 2, i + 6), 16));
i += 6;
} else { result += str[i]; i++; }
break;
default: result += str[i + 1]; i += 2; break;
}
} else {
result += str[i]; i++;
}
}
return result;
}
/* CSV */
function escapeCSV(str) {
if (str.indexOf('"') !== -1 || str.indexOf(',') !== -1 || str.indexOf('\n') !== -1 || str.indexOf('\r') !== -1) {
return '"' + str.replace(/"/g, '""') + '"';
}
return str;
}
function unescapeCSV(str) {
if (str.length >= 2 && str[0] === '"' && str[str.length - 1] === '"') {
return str.slice(1, -1).replace(/""/g, '"');
}
return str;
}
/* SQL */
function escapeSQL(str) {
return str.replace(/'/g, "''");
}
function unescapeSQL(str) {
return str.replace(/''/g, "'");
}
/* ---- Utility ---- */
function copyOutput() {
const text = document.getElementById('output').value;
if (text) { navigator.clipboard.writeText(text); showToast(); }
}
function showToast() {
const t = document.getElementById('copy-toast');
t.classList.add('show');
setTimeout(() => t.classList.remove('show'), 1800);
}
function toggleFaq(el) { el.parentElement.classList.toggle('open'); }
</script>
<script>document.addEventListener('click',e=>{const dd=document.getElementById('tools-dropdown');if(dd&&!dd.contains(e.target))dd.classList.remove('open')});</script>
</body>
</html>