有没有一种方法可以将 HTML 转换为普通文本,而无需使用 Jquery 将其实际写入选择器?

发布于 2024-12-18 21:54:26 字数 649 浏览 1 评论 0原文

目前我的理解是,在Jquery中,通过html()函数,我们可以将HTML转换为文本,例如

$("#myDiv").html(result);

将“result”(即html代码)转换为普通文本并在myDiv中显示。

现在,我的问题是,有没有一种方法可以简单地转换 html 并将其放入变量中?

例如:

var temp;
temp = html(result);

像这样的东西,当然这不起作用,但是如何将转换后的结果放入变量而不将其写入屏幕?由于我正在循环中检查转换后的结果,因此认为如果继续将每个循环都将其写入屏幕,那就太浪费资源了。

编辑:

抱歉造成混淆,例如,如果结果是 "

abc

"$(#mydiv).html( result) 使 mydiv 显示 "abc",通过删除

标签将 html“转换”为普通文本。那么如何将 "abc" 放入变量中而不执行 var temp=$(#mydiv).text() 之类的操作?

I understand so far that in Jquery, with html() function, we can convert HTML into text, for example,

$("#myDiv").html(result);

converts "result" (which is the html code) into normal text and display it in myDiv.

Now, my question is, is there a way I can simply convert the html and put it into a variable?

for example:

var temp;
temp = html(result);

something like this, of course this does not work, but how can I put the converted into a variable without write it to the screen? Since I'm checking the converted in a loop, thought it's quite and waste of resource if keep writing it to the screen for every single loop.

Edit:

Sorry for the confusion, for example, if result is " <p>abc</p> " then $(#mydiv).html(result) makes mydiv display "abc", which "converts" html into normal text by removing the <p> tags. So how can I put "abc" into a variable without doing something like var temp=$(#mydiv).text()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

心碎无痕… 2024-12-25 21:54:26

这是非 jQuery 解决方案:

function htmlToText(html) {
    var temp = document.createElement('div');
    temp.innerHTML = html;
    return temp.textContent; // Or return temp.innerText if you need to return only visible text. It's slower.
}

在 IE ≥9 中效果很好。

Here is no-jQuery solution:

function htmlToText(html) {
    var temp = document.createElement('div');
    temp.innerHTML = html;
    return temp.textContent; // Or return temp.innerText if you need to return only visible text. It's slower.
}

Works great in IE ≥9.

深海蓝天 2024-12-25 21:54:26

不,html 方法不会将 HTML 代码转换为文本,而是将 HTML 代码转换为 DOM 元素。浏览器将解析 HTML 代码并从中创建元素。

您不必将 HTML 代码放入页面中即可将其解析为元素,您可以在独立元素中执行此操作:

var d = $('<div>').html(result);

现在您有一个 jQuery 对象,其中包含一个 div 元素,该元素具有解析后的 H​​TML 代码中的元素作为子元素。或者:

var d = $(result);

现在您有一个 jQuery 对象,其中包含已解析的 HTML 代码中的元素。

No, the html method doesn't turn HTML code into text, it turns HTML code into DOM elements. The browser will parse the HTML code and create elements from it.

You don't have to put the HTML code into the page to have it parsed into elements, you can do that in an independent element:

var d = $('<div>').html(result);

Now you have a jQuery object that contains a div element that has the elements from the parsed HTML code as children. Or:

var d = $(result);

Now you have a jQuery object that contains the elements from the parsed HTML code.

雨的味道风的声音 2024-12-25 21:54:26

您可以简单地删除所有 HTML 标签:

var text = html.replace(/(<([^>]+)>)/g, "");

You could simply strip all HTML tags:

var text = html.replace(/(<([^>]+)>)/g, "");
弥枳 2024-12-25 21:54:26

你可以尝试:

var tmp = $("<div>").attr("style","display:none");
var html_text = tmp.html(result).text();
tmp.remove();

但是用正则表达式修改字符串的方式更简单,因为它不使用DOM遍历。

您可以使用正则表达式将 html 替换为文本字符串,就像用户 Crozin 的回答一样。

附注
另外,您可能喜欢
替换为换行符的方式:

var text = html.replace(/<\s*br[^>]?>/,'\n')
            .replace(/(<([^>]+)>)/g, "");

you can try:

var tmp = $("<div>").attr("style","display:none");
var html_text = tmp.html(result).text();
tmp.remove();

But the way with modifying string with regular expression is simpler, because it doesn't use DOM traversal.

You may replace html to text string with regexp like in answer of user Crozin.

P.S.
Also you may like the way when <br> is replacing with newline-symbols:

var text = html.replace(/<\s*br[^>]?>/,'\n')
            .replace(/(<([^>]+)>)/g, "");
放手` 2024-12-25 21:54:26

为什么不使用 .text()

$("#myDiv").html($(result).text());

Why not use .text()

$("#myDiv").html($(result).text());
孤千羽 2024-12-25 21:54:26

var temp = $(your_selector).html();

变量 temp 是一个包含 HTML 的字符串

var temp = $(your_selector).html();

the variable temp is a string containing the HTML

-小熊_ 2024-12-25 21:54:26

$("#myDiv").html(result); 未将文本格式化为 html 代码。您可以使用 .html() 来做一些事情。

如果您说 $("#myDiv").html(); ,但您没有将参数传递给 `html()' 函数,那么您正在“获取”当前所在的 html div 元素。
所以你可以说,

var whatsInThisDiv = $("#myDiv").html();
console.log(whatsInThisDiv); //will print whatever is nested inside of <div id="myDiv"></div>

如果你在 .html() 调用中传递一个参数,你将把 html 设置为存储在你传递的变量或字符串中的内容。例如,

var htmlToReplaceCurrent = '<div id="childOfmyDiv">Hi! Im a child.</div>';
$("#myDiv").html(htmlToReplaceCurrent);

这会让你的 dom 看起来像这样......

<div id="myDiv">
    <div id="childOfmyDiv">Hi! Im a child.</div>
</div>

$("#myDiv").html(result); is not formatting text into html code. You can use .html() to do a couple of things.

if you say $("#myDiv").html(); where you are not passing in parameters to the `html()' function then you are "GETTING" the html that is currently in that div element.
so you could say,

var whatsInThisDiv = $("#myDiv").html();
console.log(whatsInThisDiv); //will print whatever is nested inside of <div id="myDiv"></div>

if you pass in a parameter with your .html() call you will be setting the html to what is stored inside the variable or string you pass. For instance

var htmlToReplaceCurrent = '<div id="childOfmyDiv">Hi! Im a child.</div>';
$("#myDiv").html(htmlToReplaceCurrent);

That will leave your dom looking like this...

<div id="myDiv">
    <div id="childOfmyDiv">Hi! Im a child.</div>
</div>
夏花。依旧 2024-12-25 21:54:26

最简单、安全的解决方案 - 使用 Dom Parser

对于更高级的用法 - 我建议您尝试 Dompurify

它是跨浏览器的(并且支持 Node js)。只有 19kb gziped

这是我创建的一个 fiddle ,它将 HTML 转换为文本

const dirty = "Hello <script>in script<\/script> <b>world</b><p> Many other <br/>tags are stripped</p>";
const config = { ALLOWED_TAGS: [''], KEEP_CONTENT: true, USE_PROFILES: { html: true }  };
// Clean HTML string and write into the div
const clean = DOMPurify.sanitize(dirty, config);
document.getElementById('sanitized').innerText = clean;

输入:<代码>Hello

输出:Hello world许多其他标签被剥离

Easiest, safe solution - use Dom Parser

For more advanced usage - I suggest you try Dompurify

It's cross-browser (and supports Node js). only 19kb gziped

Here is a fiddle I've created that converts HTML to text

const dirty = "Hello <script>in script<\/script> <b>world</b><p> Many other <br/>tags are stripped</p>";
const config = { ALLOWED_TAGS: [''], KEEP_CONTENT: true, USE_PROFILES: { html: true }  };
// Clean HTML string and write into the div
const clean = DOMPurify.sanitize(dirty, config);
document.getElementById('sanitized').innerText = clean;

Input: Hello <script>in script<\/script> <b>world</b><p> Many other <br/>tags are stripped</p>

Output: Hello world Many other tags are stripped

从来不烧饼 2024-12-25 21:54:26

使用 dom 有几个缺点。其他答案中未提及的一个:媒体将被加载,导致网络流量。

我建议在将某些标签(如 br、p、ol、ul 和标题)替换为 \n 换行符后使用正则表达式来删除标签。

Using the dom has several disadvantages. The one not mentioned in the other answers: Media will be loaded, causing network traffic.

I recommend using a regular expression to remove the tags after replacing certain tags like br, p, ol, ul, and headers into \n newlines.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文