Skip to content

Commit 03873e8

Browse files
committed
add Replacing HTML tags with HTML named entities
1 parent e94f5b0 commit 03873e8

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
---
2+
layout: recipe
3+
title: Replacing HTML tags with HTML named entities
4+
chapter: Regular Expressions
5+
---
6+
## Problem
7+
8+
You need to replace HTML tags with named entities:
9+
10+
`<br/> => &lt;br/&gt;`
11+
12+
## Solution
13+
14+
{% highlight coffeescript %}
15+
htmlEncode = (str) ->
16+
str.replace /[&<>"']/g, ($0) ->
17+
"&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";"
18+
19+
htmlEncode('<a href="http://bn.com">Barnes & Noble</a>')
20+
# => '&lt;a href=&quot;http://bn.com&quot;&gt;Barnes &amp; Noble&lt;/a&gt;'
21+
{% endhighlight %}
22+
23+
## Discussion
24+
25+
There are probably better ways to implement the above method.

wanted-recipes.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,6 @@ foo 1, 2, 3
8787
* Searching for substrings # "foo bar baz".match(/ba./) # => [ 'bar', index: 4, input: 'foo bar baz' ]
8888
* Searching for substrings # "foo bar baz".search(/ba./) # => 4
8989
* Replacing substrings # "foo bar baz".replace( /ba./, 'foo') # => "foo foo baz"
90-
* Replace HTML tags with named HTML entities # <br/> => &lt;br/&gt;
9190

9291
## Networking
9392

0 commit comments

Comments
 (0)