1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Js 正则表达式截取html内容 如何从JavaScript中的字符串中剥离HTML(仅提取文本内容)...

Js 正则表达式截取html内容 如何从JavaScript中的字符串中剥离HTML(仅提取文本内容)...

时间:2021-03-14 05:42:59

相关推荐

Js 正则表达式截取html内容 如何从JavaScript中的字符串中剥离HTML(仅提取文本内容)...

本文概述

通常, 在服务器端, 你可以使用一系列PHP函数(例如strip_tags)并删除HTML和难看的格式。但是, 如果你无法使用服务器(或使用Node.js)来完成此任务, 则仍可以使用Javascript来完成。在本文中, 你将找到3种从Javascript字符串中剥离html标签的方法。

1.创建一个临时DOM元素并检索文本

这是使用Javascript从字符串中剥离HTML的首选(推荐)方法。临时div元素的内容将是要剥离的Providen HTML字符串, 然后从div元素返回innerText属性:

/**

* Returns the text from a HTML string

*

* @param {html} String The html string

*/

function stripHtml(html){

// Create a new div element

var temporalDivElement = document.createElement("div");

// Set the HTML content with the providen

temporalDivElement.innerHTML = html;

// Retrieve the text property of the element (cross-browser support)

return temporalDivElement.textContent || temporalDivElement.innerText || "";

}

var htmlString= "

Hello World

\n

It's me, Mario

";

//Hello World

//It's me, Mario

console.log(stripHtml(htmlString));

唯一的问题(和优点)是浏览器将把Providen字符串当作HTML来处理, 这意味着, 如果HTML字符串包含浏览器的某种类型的可解释Javascript, 则它将被执行:

// This won't do anything but retrieve the text

stripHtml("")

// But this ...

stripHtml("")

因此, 仅当你信任HTML字符串的来源时, 才应使用此选项。

2.如果你使用的是jQuery

如果你使用jQuery, 则可以从第一步开始简化代码。以下代码与第一步中的代码相同(警告也适用):

var htmlString= "

\n

Hello World

\n

This is the text that we should get.

\n

Our Code World ©

\n ";

var stripedHtml = $("

").html(htmlString).text();

// Hello World

// This is the text that we should get.

// Our Code World ©

console.log(stripedHtml);

3.使用正则表达式

如果你在没有文档或createElement方法的节点环境中工作, 则可以使用正则表达式替换字符串中的所有HTML标记:

var htmlString= "

Hello World

\n

It's me, Mario

";

var stripedHtml = htmlString.replace(/]+>/g, '');

//Hello World

//It's me, Mario

console.log(stripedHtml);

此方法将完美地工作, 但是只会删除小于和大于符号(), 这意味着不会从字符串中删除html实体, 如以下示例所示:

var htmlString= "

\n

Hello World

\n

This is the text that we should get.

\n

Our Code World ©

\n ";

var stripedHtml = htmlString.replace(/]+>/g, '');

// Hello World

// This is the text that we should get.

// Our Code World ©

console.log(stripedHtml);

©实体应翻译为版权符号, 但仍作为html实体存在。如果将其与第一种方法进行比较, 显然这是一个缺点, 但是请不要担心不会丢失所有内容(尚未)。你可以使用Javascript将htmlentities解码为可读的字符(阅读本文以了解如何实现)。以下示例将使用前面提到的replace指令剥离所有html, 并使用he库将htmlentity转换为人类可读的字符:

var htmlString= "

\n

Hello World

\n

This is the text that we should get.

\n

Our Code World ©

\n ";

var stripedHtml = htmlString.replace(/]+>/g, '');

var decodedStripedHtml = he.decode(stripedHtml);

// Hello World

// This is the text that we should get.

// Our Code World ©

console.log(stripedHtml);

// Hello World

// This is the text that we should get.

// Our Code World ©

console.log(decodedStripedHtml);

如你所见, 使用he库, 我们将剩余的html实体转换为可读的值。请注意, 你不必使用he库, 因为如果你阅读本文, 则可以创建自己的解码htmlentities函数。

编码愉快!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。