Skip to Content
JavaScript 经典实例:第三版
book

JavaScript 经典实例:第三版

by Adam D. Scott, Matthew MacDonald, Shelley Powers
September 2022
Intermediate to advanced
585 pages
8h 17m
Chinese
China Electric Power Press Ltd.
Content preview from JavaScript 经典实例:第三版
62
2
2.8.4
参考
除了直接替换之外,还可以在字符串中找出匹配的子串,一一检查,详见
2.11
节和
2.12
节。
2.9
HTML
标签替换为具名实体
2.9.1
问题
你想把转义后的标记插入网页(浏览器显示尖括号,而不解释为
HTML
标签)。之
所以这么做,可能是因为你想展示一段
HTML
标记示例,比如说在一篇教程文章中;
也有可能是因为你想确保安全,清洗外部数据,例如由用户提交的文本或者从数据
库中获取的文本。
2.9.2
方案
使用
String.replaceAll()
方法把尖括号(
<>
替换为
HTML
具名实体
&lt;
&gt;
。整
个过程分为两步,分别替换两个尖括号。
const
originalPieceOfHtml = '<p>This is a <span>paragraph</span></p>';
//
去掉
<
字符,得到一个新字符串
let
safePieceOfHtml = originalPieceOfHtml.replaceAll('<', '&lt;');
//
去掉
>
字符,得到一个新字符串
safePieceOfHtml = safePieceOfHtml.replaceAll('>', '&gt;');
//
在页面中展示
document.getElementById('placeholder').innerHtml = safePieceOfHtml;
现在,查看这个字符串,你会发现其中的文本为“
<p>This is a <span>paragraph</
span></p> ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

JavaScript

JavaScript

T. J. Crowder
JavaScript

JavaScript

David Flanagan
JavaScript Patterns

JavaScript Patterns

Stoyan Stefanov

Publisher Resources

ISBN: 9787519869601